Search code examples
c#stringdoubleint32

"value was not in a correct format" error when converting a string to an int32


this is my code;

string a="11.4";

int b,c;

b=2;

c= convert.toint32(a) * b

I get this error;

Input string was not in a correct format

how can i convert "a"?


Solution

  • Well a is just not an integer value - you could use Convert.ToDouble() instead. To guard against parsing errors in case that is a possibility use double.TryParse() instead:

    string a = "11.4";
    double d;
    
    if (double.TryParse(a, out d))
    {
        //d now contains the double value
    }
    

    Edit:

    Taking the comments into account, of course it is always best to specify the culture settings. Here an example using culture-indepenent settings with double.TryParse() which would result in 11.4 as result:

    if (double.TryParse(a, NumberStyles.Number, CultureInfo.InvariantCulture, out d))
    {
        //d now contains the double value
    }