开发者

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

开发者 https://www.devze.com 2022-12-30 17:29 出处:网络
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 separa开发者_StackOverflow中文版tor.

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 separa开发者_StackOverflow中文版tor.

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.


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.TryParsehas an overload taking an IFormatProvider. Use a coresponding CultureInfo, in your case CultureInfo.InvariantCulture can be used.


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

精彩评论

暂无评论...
验证码 换一张
取 消