float.Parse对小数和逗号失败 [英] float.Parse fails on decimals and commas

查看:1379
本文介绍了float.Parse对小数和逗号失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试这一行:

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



其中val是设置一个字符串为5.267不带引号,我得到这个错误:

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

FormatException:未知字符。
System.Double.Parse(System.String S,风格的NumberStyles,供应商的IFormatProvider)
System.Single.Parse(System.String S,风格的NumberStyles)

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

于是,我试图改变小数点为逗号,如:5267,并得到这个错误:

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

FormatException:未知字符:,
系统。 Double.Parse(System.String S,风格的NumberStyles,供应商的IFormatProvider)
System.Single.Parse(System.String S,风格的NumberStyles)

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?

推荐答案

解析是文化意识。如果您当地的文化有不同的要求,那么你可能想通过在文化或其他格式提供。请尝试使用 CultureInfo.InvariantCulture 。您不需要,如果你做的十进制选项。

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);

这篇关于float.Parse对小数和逗号失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆