繁体   English   中英

有没有一种方法可以将转换为浮点数的String与实际的浮点值比较为if语句?

[英]Is there a way to compare a String converted into a float with an actual float value into an if-statement?

验证按钮时,我将String值转换为浮点数,但是当我尝试将转换后的值与实际的浮点数进行比较时,出现编译错误。 如果不想在应用程序中写入小于50的值,我想在此进行比较。

private void tbBid_Validating(object sender, CancelEventArgs e)
        {
            var amount = 12345678.0f;
            tbBid.Text = amount.ToString();
            if(amount.ToString()<50)
            {
                e.Cancel = true;

                epbid.SetError(tbBid,">50 lei");
            }

        }

尝试这个

//Reading value from text box
var amount = tbBid.Text;
//Parsing to float
float amountFloat = float.Parse(amount);

//Comparison
if (amountFloat < 50.0f)
{
      // Do your cancellation stuff
}

我对此做了一个简化版,可能会对您有所帮助。 我使用了您提供的代码和一个版本,其中amount首先是一个字符串值:

    // current example simplified
    float amount = 12345678.0f;
    string text = amount.ToString();
    if(amount < 50)
    {
        Console.WriteLine("Congratulations the first comparison worked!");
    }

    //if amount was a string to start with
    string amountText = "12345678.0";       
    float amountFloat;
    float.TryParse(amountText, out amountFloat);
    if(amountFloat < 50)
    {
        Console.WriteLine("Congratulations the second comparison worked!");
    }

这是.Net小提琴: https : //dotnetfiddle.net/utyWUc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM