Why double.TryParse(“0.0000”, out doubleValue) ret

2019-03-11 16:19发布

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 strings e.g. "5" it parses correctly to value of 5 .

Any ideas why it is happening ?

9条回答
神经病院院长
2楼-- · 2019-03-11 16:54

It works for me:

double temp = 0;
Console.WriteLine(double.TryParse("0.0000", out temp));
Console.ReadLine();

writes True.

查看更多
走好不送
3楼-- · 2019-03-11 16:57

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

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
查看更多
小情绪 Triste *
4楼-- · 2019-03-11 16:59

Almost certainly the problem is that Thread.CurrentCulture does not use dot as the decimal separator.

If you know that the number will be always formatted with dot as the decimal separator, use this code that utilizes the other overload of double.TryParse:

style = NumberStyles.Float | NumberStyles.AllowThousands;
culture = CultureInfo.InvariantCulture;
float num;
if (double.TryParse("0.0000", style, culture, out num)) {
    // whatever
}
查看更多
登录 后发表回答