Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToDouble throws System.FormatException for some unknown reason

Tags:

c#

.net

parsing

I am parsing an xml file and I am trying to assign a value which I is read from xml file into a double variable.

here is what my code looks like:

double someDouble = Convert.ToDouble(someString);

problem here is, when executing this line of code, i get

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format.

When I debug, i see that the value of someString is "45.00000000" in the "Locals" view.

As far as I know Convert.ToDouble supports such converting strings into double.

NOTE: just to be sure I also tried

double someDouble = Convert.ToDouble(someString.Trim('"'));
like image 323
Hayri Uğur Koltuk Avatar asked Nov 26 '25 11:11

Hayri Uğur Koltuk


2 Answers

It works fine for me.

My psychic debugging skills tell me that you're running in a culture that uses , as the decimal separator.
Pass CultureInfo.InvariantCulture.

like image 115
SLaks Avatar answered Nov 28 '25 02:11

SLaks


The code you wrote should work so long as the string being converted is actually a number. Maybe there is a non-number somewhere in the string that you are not seeing. That is the only thing that I can think of.

This won't solve your particular problem but I would recommend Double.TryParse instead of Convert.ToDouble. You largely eliminate the chance that an exception will be thrown with Double.TryParse

like image 30
Chase Avatar answered Nov 28 '25 01:11

Chase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!