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

StackOverflow https://stackoverflow.com/questions/9027204

  •  14-11-2019
  •  | 
  •  

سؤال

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;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top