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?
ToDouble(Single) Converts the value of the specified single-precision floating-point number to an equivalent double-precision floating-point number.
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.
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
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"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With