when i run the following code it always throws an exception
string a = "-12.12";
double b = Convert.ToDouble(a);
An exception of type 'System.FormatException' occurred in mscorlib.ni.dll but was not handled in user code
what is the problem with the code ?
I strongly suspect you're running in a locale which uses ,
as the decimal separator... or which uses a different symbol for negation. You can pass in a CultureInfo
to specify how to parse - I usually use double.Parse
instead of Convert.ToDouble
:
double x = double.Parse(a, CultureInfo.InvariantCulture);
That will be absolutely fine. If it still doesn't work, that suggests your actual string isn't quite "-12.12". For example, if the "-" is actually an en-dash or something like that, it won't parse properly.
See more on this question at Stackoverflow