Why does Convert.ToDouble change the value 1000 times?

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

The coordinates look like this: 3.47 , -1.54 , .., etc.

When I assign a value to a double variable

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

The value becomes 3470.00

Why is this so?

+5
source share
2 answers

As already mentioned, the problem lies in the culture settings. XML is supposed to work with an invariant culture, so you should not use the Convert class (although you can by passing CultureInfo.InvariantCulture in every call that you can easily forget), but specifically for this purpose the XmlConvert Class , which covers both write and read conversions required for XML content.

So in your case you really should use

 x = XmlConvert.ToDouble(reader["X"]); 
+3
source

Convert.ToDouble uses the default CurrentCulture settings if you do not supply an IFormatProvider .

It looks like your CurrentCulture not using . like NumberDecimalSeparator , but it is probably used as NumberGroupSeparator . Therefore, your string was processed as 3400 not 3.4

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

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

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

You can use the double.Parse method for double.Parse .

 double x; x = double.Parse("-1.54", NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); // x will be -1.54 
+11
source

Source: https://habr.com/ru/post/1238513/


All Articles