Double.TryParse() input decimal separator differen

2019-02-12 14:40发布

问题:

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.

回答1:

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);


回答2:

This does the job:

    string test = "0.7";
    Assert.Equal(0.7, Double.Parse(test, NumberStyles.Float, CultureInfo.InvariantCulture));


回答3:

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



回答4:

Easy way to specify custom decimal separator:

var price = "122$00";
var nfi = new NumberFormatInfo { CurrencyDecimalSeparator = "$" };
var ok = decimal.TryParse(price, NumberStyles.Currency, nfi, out result);