0

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

GarethJ
  • 6,496
  • 32
  • 42
Mehmet
  • 149
  • 1
  • 3
  • 12

2 Answers2

4

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
}
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • 3
    Side note: depending on culture settings 11.4 may actually parse OK as integer (if "." is group separator); it may as well fail to parse as double (if decimal separator is ","). It is good practice to specify culture when parsing values. – Alexei Levenkov Jan 26 '12 at 23:58
  • @BrokenGlass, what do you expect for `d`? `11.4` or `114.0`? Both are correct depending on the culture. Getting an exception `Input string was not in a correct format` is more safer than the wrong value – L.B Jan 27 '12 at 00:41
1

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;
JXITC
  • 1,110
  • 1
  • 13
  • 27
  • And My VS2010 debugger says `ans=228.0`. Read Alexei Levenkov's comment – L.B Jan 27 '12 at 00:18
  • @L.B 228.0? it's weird. Have you tried to break down the code and step through to find out exactly what each variable's value? – JXITC Jan 27 '12 at 00:22
  • 1
    Not weird. Just add this line before your code `Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("tr-TR");` or `Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("de-DE");` – L.B Jan 27 '12 at 00:32
  • @L.B Oh I got it after read Alexei's comment. Thank you for reminding! :) – JXITC Jan 27 '12 at 00:34