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

前端 未结 4 1199
眼角桃花
眼角桃花 2021-01-04 14:42

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,

相关标签:
4条回答
  • 2021-01-04 15:05

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

    0 讨论(0)
  • 2021-01-04 15:09

    This does the job:

        string test = "0.7";
        Assert.Equal(0.7, Double.Parse(test, NumberStyles.Float, CultureInfo.InvariantCulture));
    
    0 讨论(0)
  • 2021-01-04 15:26

    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 讨论(0)
  • 2021-01-04 15:31

    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);
    
    0 讨论(0)
提交回复
热议问题