简体   繁体   English

将String解析为double时发生System.FormatException

[英]System.FormatException when parsing String to double

the Code worked fine in Unity. 该代码在Unity中运行良好。 Now I'm using the samecode in a console Project and im getting a System.FormatException exception. 现在,我在控制台项目中使用相同的代码,并收到System.FormatException异常。

The code is: 代码是:

private double ConvertToNumber(string number)
        {      
            return double.Parse(number, numberStyle);
        }

parameter when calling are: 调用时的参数为:

number = "3.138924e-002"
numberStyle = NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign

Does anyone see the Error, or knows what might caus this? 有人看到错误,还是知道可能是什么原因造成的?

The exception is thrown because the string you are providing cannot be converted to a number using the format you specified and your own current cultrue . 抛出异常是因为无法使用您指定的格式和您自己的当前cultrue将提供的字符串转换为数字。 The latter is implict unless you specify it. 除非您指定,否则后者是隐含的。

If you are reading this value from a database, you should use the invariant culture (ie a culture designed to persist numbers and dates in a consistent way in whatever place you need, except user interfaces). 如果要从数据库读取此值,则应使用不变区域性(即,用于在用户所需的任何位置(用户界面除外)以一致的方式持久存储数字和日期的区域性)。

Your code becomes: 您的代码变为:

return double.Parse(number, numberStyle, System.Globalization.CultureInfo.InvariantCulture);

Instead, if you need a specific culture, you need to pass the correct culture in place of the invariant one. 相反,如果您需要一种特定的文化,则需要传递正确的文化来代替不变的文化。

@ Selvin关于CultureInfo.InvariantCulture是正确的,将其添加为参数可以修复错误。

return double.Parse(number, numberStyle, CultureInfo.InvariantCulture);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM