Search code examples
c#parsingformatexception

Why do I get a Format Exception when comparing int and float values?


I don't know why but I am getting a FormatException when comparing two values. Could someone tell me what I am doing wrong? I already tried to make both values float, yet the same exception...

float label1 = float.Parse(label15.Text);
int box1 = int.Parse(textBox23.Text);

if (label1 <= box1)
{
    //Do things"
}

Solution

  • You've got yourself in a corner without using proper exception handling.

        float label1 = float.Parse(label15.Text);  //problem 1
        int box1 = int.Parse(label15.Text);  //problem 2
    
        if (label1 <= box1)  //problem 3
        {
        //Do things"
        }
    

    Problems 1 and 2 are that you aren't ensuring your UI is giving you values that you can parse. That will throw exceptions. Problem 3 is that since you don't know if your parsing was successful, you don't know if you can even make the comparison. Try TryParse().

        float label1 = 0;
    
                    int box1 = 0;
    
                    if(float.TryParse(label15.Text, out label1)
                        &&  int.TryParse(label15.Text, out box1))
                    {
                       if (label1 <= box1)
                       {
                       //Do things"
                       }
                    }
    

    The TryParse() function populates your existing variables as out parameters, but returns a bool. This returns as false if the parse fails, and allows the code to continue. By making these succeeding an if condition, we sidestep errors entirely.

    You can also always wrap your code in a try-catch block to determine the cause of any exception and generate output, but you never want that to manage your logical flow. You'd use that to troubleshoot this problem, and what I posted as a possible solution.