How to convert string with exponent to float?

自作多情 提交于 2019-12-11 14:08:21

问题


I have the following string: "3.39112632978e+001" which I need to convert to float. WolframAlpha says that the result of this value is 33.9112632978 which evidently I should get somehow and I couldn't figure out how.

Single.Parse("3.39112632978e+001") gives 3.39112624E+12

Double.Parse("3.39112632978e+001") gives 3391126329780.0

float.Parse("3.39112632978e+001") gives 3.39112624E+12

What should I do?


回答1:


You are experiencing a localization issue wherein the . is being interpreted as a thousands separator instead of as a decimal separator. Are you in, say, Europe?

Try this:

float f = Single.Parse("3.39112632978e+001", CultureInfo.InvariantCulture);
Console.WriteLine(f);

Output:

33.91126

Note that if we replace the . by a , then we see the behavior that you are experiencing:

float g = Single.Parse("3,39112632978e+001", CultureInfo.InvariantCulture);
Console.WriteLine(g);

Output:

3.391126E+12

This supports my belief that you are experiencing a localization issue.




回答2:


I think, this thread gives hints to your question: http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/e482cda0-6510-4d2c-b830-11e57e04f65d (and the System.Globalization.NumberStyles.Float is one of the key things here - it changes how the . is interpreted)



来源:https://stackoverflow.com/questions/2238070/how-to-convert-string-with-exponent-to-float

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