简体   繁体   中英

“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"?

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
}

A very first glance, the number literal "11.4" is not a actual "int". Try some other converting format, such as ToDouble()

I have tried following code in C# for your reference.

        string a = "11.4";
        double num_a = Convert.ToDouble(a);
        int b = 2;
        double ans = num_a * b;

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