Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double.TryParse() input decimal separator different than system decimal separator

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.

like image 805
mare Avatar asked May 16 '10 17:05

mare


People also ask

What does the Double TryParse do?

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.

What does Decimal TryParse do?

TryParse(String, Decimal) Converts the string representation of a number to its Decimal equivalent. A return value indicates whether the conversion succeeded or failed.


3 Answers

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);
like image 138
Chris Taylor Avatar answered Sep 22 '22 13:09

Chris Taylor


This does the job:

    string test = "0.7";
    Assert.Equal(0.7, Double.Parse(test, NumberStyles.Float, CultureInfo.InvariantCulture));
like image 44
asgerhallas Avatar answered Sep 22 '22 13:09

asgerhallas


double.TryParsehas an overload taking an IFormatProvider. Use a coresponding CultureInfo, in your case CultureInfo.InvariantCulture can be used.

like image 33
Femaref Avatar answered Sep 22 '22 13:09

Femaref