Why double.TryParse(“0.0000”, out doubleValue) returns false ?

后端 未结 9 621
一个人的身影
一个人的身影 2021-02-03 20:38

I am trying to parse string \"0.0000\" with double.TryParse() but I have no idea why would it return false in this particular example. When I pass integer-like stri

相关标签:
9条回答
  • 2021-02-03 21:24

    The most stupid thing about this is that it only accept "," as decimal separator in my culture, but the result is with a ".". Someone, somewhere, wasn't very lucky thinking that day... So I'll try this:

    if ((double.TryParse(sVat, out vat)) == false)
        if (double.TryParse(sVat.Replace(",", "."), out vat) == false)
          double.TryParse(sVat.Replace(".", ","), out vat);
    
    0 讨论(0)
  • 2021-02-03 21:26

    To change the culture to something that has "." as decimal separator use:

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
    
    0 讨论(0)
  • 2021-02-03 21:27

    TryParse uses the current culture by default. And if your current culture uses a decimal seperator different from ., it can't parse 0.0000 as you intend. So you need to pass in CultureInfo.InvariantCulture.

    var numberStyle = NumberStyles.AllowLeadingWhite |
                     NumberStyles.AllowTrailingWhite |
                     NumberStyles.AllowLeadingSign |
                     NumberStyles.AllowDecimalPoint |
                     NumberStyles.AllowThousands |
                     NumberStyles.AllowExponent;//Choose what you need
    double.TryParse( "0.0000", numberStyle, CultureInfo.InvariantCulture, out myVar)
    
    0 讨论(0)
提交回复
热议问题