float.Parse fails on decimals and commas

2019-02-06 14:01发布

When I try this line:

float f = float.Parse(val, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands);

where val is a string set to "5.267" without the quotes, I get this error:

FormatException: Unknown char: . System.Double.Parse (System.String s, NumberStyles style, IFormatProvider provider) System.Single.Parse (System.String s, NumberStyles style)

So I tried changing the decimal point to a comma, like: 5,267 and got this error:

FormatException: Unknown char: , System.Double.Parse (System.String s, NumberStyles style, IFormatProvider provider) System.Single.Parse (System.String s, NumberStyles style)

I....don't....understand. As far as I can tell I'm doing this right. It's a simple thing, so why is it giving me such grief?

标签: c# parsing
1条回答
霸刀☆藐视天下
2楼-- · 2019-02-06 14:56

Parse is culture aware. If your local culture has different requirements, then you may want to pass a culture or other format provider in. Try using CultureInfo.InvariantCulture. You won't need the decimal option if you do.

float f = float.Parse(val,
                      System.Globalization.NumberStyles.AllowThousands,
                      CultureInfo.InvariantCulture);
查看更多
登录 后发表回答