Home > Mobile >  Input string was not in a correct format_ C#
Input string was not in a correct format_ C#

Time:10-04

I have a field which displays negative number(Example -100.00)

I wrote the following code to convert string to int. However while debugging I am getting the following error : Input string was not in a correct format.

             var GetValue = driver.FindElement(By.Id("txtTotal")).GetAttribute("value");
            
            // convert string to int
            int TValue = int.Parse(GetValue , NumberStyles.AllowLeadingSign| NumberStyles.AllowParentheses);

                
            if (TValue > 0)
            {
                throw new Exception("In this method should return a negative value");
            }
            else
            {
                Console.WriteLine("good");
            }

Can anyone help me on this please. Thanks.

CodePudding user response:

Error which you are getting is self explanatory. If you look at closely you are trying to convert float number(of type string) to an integer. If you try to convert GetValue to double/float, then it will work.

Use .TryParse() instead of Parse() to check conversion is worked or not.

var GetValue = driver.FindElement(By.Id("txtTotal")).GetAttribute("value");
if(double.TryParse(GetValue, out double total)
   Console.WriteLine("good");
else
   throw new Exception("In this method should return a negative value");
  • Related