views:

274

answers:

2

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?

+3  A: 

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)

naivists
+3  A: 

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.

Jason