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

后端 未结 9 646
一个人的身影
一个人的身影 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:12

    It will return false if the current culture specifies a decimal point separator that is different than the . character.

    When parsing strings representation you need to be aware in what culture they are represented otherwise you'll get unexpected behavior.

    In this case you're getting false, but it could even be worse, for example in the following example if you were expecting to get the number one you would instead get one thousand:

    Thread.CurrentThread.CurrentCulture = new CultureInfo("pt-PT");
    
    double d;
    Console.WriteLine(double.TryParse("1.000", out d));
    Console.WriteLine(d);
    

    This is because in the pt-PT culture the . character is used as NumberGroupSeparator and the , character is used as NumberDecimalSeparator.

    If the input you're parsing comes from the user then always parse it using the culture the user is associated. Getting the culture the user is associated is something dependent on the context, for example in a Windows Forms application you would use Thread.CurrentThread.CurrentCulture when on the UI thread to get it. In a ASP.NET application this may be different.

提交回复
热议问题