Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Convert.ToDouble change my Value by factor 1000?

I am reading some x and y coordinates from an XML file.

The coordinates look like this 3.47, -1.54, .. and so on.

When I assign the value to a double variable by

double x, y;
x = Convert.ToDouble(reader["X"]); // X Value: 3.47

The Value becomes 3470.00

Why is this the case?

like image 889
ManuKaracho Avatar asked Dec 17 '15 11:12

ManuKaracho


People also ask

What is Convert ToDouble?

ToDouble(Single) Converts the value of the specified single-precision floating-point number to an equivalent double-precision floating-point number.

Can we convert decimal to double in C#?

You can also convert a Decimal to a Double value by using the Explicit assignment operator. Because the conversion can entail a loss of precision, you must use a casting operator in C# or a conversion function in Visual Basic.


2 Answers

Convert.ToDouble method uses your CurrentCulture settings by default if you don't supply any IFormatProvider.

Looks like your CurrentCulture does not use . as a NumberDecimalSeparator but it probably uses as a NumberGroupSeparator. That's why your string parsed as 3400 not 3.4

As a solution, you can use a culture that already has . as a NumberDecimalSeparator in a second parameter of your Convert.ToDouble method like InvariantCulture.

double x;
x = Convert.ToDouble("3.47", CultureInfo.InvariantCulture); // x will be 3.47 not 3470

For your -1.54 example, you need to specify to use combined AllowLeadingSign and AllowDecimalPoint styles. Unfortunately, Convert.ToDouble does not have any overload which takes NumberStyles as a parameter.

For that, you can use double.Parse method instead.

double x;
x = double.Parse("-1.54", NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint,
                 CultureInfo.InvariantCulture); // x will be -1.54
like image 80
Soner Gönül Avatar answered Oct 09 '22 06:10

Soner Gönül


As others already mentioned, the problem is the culture settings. XML is supposed to work with invariant culture, that's why you should not use Convert class (although you can, passing CultureInfo.InvariantCulture in every call, which can easily be forgotten), but a specially provided for that purpose XmlConvert Class which covers both writing and reading conversions needed for XML content.

So in your case you should really use

x = XmlConvert.ToDouble(reader["X"]);
like image 25
Ivan Stoev Avatar answered Oct 09 '22 06:10

Ivan Stoev