有没有办法将转换为浮点数的String与实际的浮点值进行比较?

问题描述 投票:0回答:2

在验证按钮时,我将String值转换为float值,但是当我尝试将转换后的值与实际的float进行比较时,我获得了编译错误。我想在此创建一个比较if,以便不允许在应用程序中写入低于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");
            }

        }
c# winforms if-statement string-conversion
2个回答
1
投票

试试这个

//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
}

1
投票

我已经制作了一个可以帮助你的简化版本。我已经使用了您提供的代码以及金额首先是字符串值的版本:

    // 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

© www.soinside.com 2019 - 2024. All rights reserved.