为什么在将字符串转换为浮点数时会出现FormatException? [英] Why do I get a FormatException when converting a string to a float?

查看:228
本文介绍了为什么在将字符串转换为浮点数时会出现FormatException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  Console.WriteLine(float.Parse(6.59))当我尝试将字符串转换为float时: ; 

引发异常:


未处理的异常:System.FormatException:输入字符串不是正确的f
或者$ .b $ System.Number.ParseSingle(String value,NumberStyles options,NumberFormat



当我尝试像这样:

  Console.WriteLine(Convert.ToSingle( 6.59)); 

引发同样的异常:


未处理的异常:System.FormatException:输入的字符串不是正确的f $ b $ ormat中。
在System.Number.ParseSingle(字符串值,NumberStyles选项,NumberFormat
的信息numfmt)

在System.Convert.ToSingle(字符串值)

你能解释为什么发生这种情况?

解决方案

单个参数Parse方法使用当前文化来解析字符串。如果您当前的文化使用其他小数点分隔符,这将失败。



尝试使用不变的文化:

 float.Parse(6.59,CultureInfo.InvariantCulture)


When I try to convert a string to float:

Console.WriteLine(float.Parse("6.59"));

it throws an exception:

Unhandled Exception: System.FormatException: Input string was not in a correct f ormat.
at System.Number.ParseSingle(String value, NumberStyles options, NumberFormat Info numfmt)

When I try it like this:

Console.WriteLine(Convert.ToSingle("6.59"));

It throws the same exception:

Unhandled Exception: System.FormatException: Input string was not in a correct f ormat.
at System.Number.ParseSingle(String value, NumberStyles options, NumberFormat Info numfmt)
at System.Convert.ToSingle(String value)

Can you explain why this happens?

解决方案

The single argument Parse method uses the current culture to parse the string. If your current culture uses some other decimal separator, this will fail.

Try using the invariant culture:

float.Parse("6.59", CultureInfo.InvariantCulture)

这篇关于为什么在将字符串转换为浮点数时会出现FormatException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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