double.Parse throw a System.FormatException

南笙酒味 提交于 2019-11-27 08:05:48

问题


I am trying to parse some string to a double value, using this parse method overload:

double.Parse("198.222213745118", CultureInfo.CurrentUICulture);

the CultureInfo.CurrentUICulture is fr-FR. but this is throwing an exception of type FormatException.

What can be the reason?


回答1:


French (i.e. fr-FR) use a comma to denote the start of the decimal part, not a period. They use a period to separate thousands.




回答2:


I know this question is old but my answer might help someone else. So this is the answer:

double.Parse("198.222213745118", System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo);

instead of

double.Parse("198.222213745118", CultureInfo.CurrentUICulture);



回答3:


I suggest using the Double.TryParse rather than the .Parse as it is safer to use and makes sure you dont get any exception on parsing.

Here is a Code for you to use,

double answer = -1;
Double.TryParse("Value", out answer);

Now all you have to do is do a conditional statement that'll check if it indeed parsed' the string.



来源:https://stackoverflow.com/questions/18847526/double-parse-throw-a-system-formatexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!