简体   繁体   中英

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

When Validating a button ,I converted the String value into a float one, but when I am trying to compare the converted value with an actual float I obtain compile errors. I want to create a comparison in this if in order to not permit values under 50 to be written in the application.

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");
            }

        }

Try this

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

I've made a simplified version of this that may help you. I've used the code you have supplied and a version where amount was a string value first:

    // 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!");
    }

Here's the .Net fiddle: https://dotnetfiddle.net/utyWUc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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