I have a source XML that uses a dot (".") as a decimal separator and I am parsing this on a system that uses a comma (",") as a decimal separator.
As a result, value of 0.7 gets parsed with Double.TryParse
or Double.Parse
as 7000000.
What are my options to parse correctly? One of them is to replace dots in source with commas with String.Replace('.', ',')
but I don't think I like this very much.
TryParse(String, Double) Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.
TryParse(String, Decimal) Converts the string representation of a number to its Decimal equivalent. A return value indicates whether the conversion succeeded or failed.
XML standard is explicit about the formatting of dates and numbers etc. This helps to ensure that the XML is platform independent and interoperable. Take a look at using XmlConvert for xml data.
double value = XmlConvert.ToDouble(stringValue);
This does the job:
string test = "0.7";
Assert.Equal(0.7, Double.Parse(test, NumberStyles.Float, CultureInfo.InvariantCulture));
double.TryParse
has an overload taking an IFormatProvider. Use a coresponding CultureInfo, in your case CultureInfo.InvariantCulture can be used.
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