33

What's the proper way to convert from a scientific notation string such as "1.234567E-06" to a floating point variable using C#?

2 Answers 2

63
Double.Parse("1.234567E-06", System.Globalization.NumberStyles.Float);
2
  • 19
    Will not work if the current culture's decimal separator is not .. So the always working approach is either using NumberStyles.Any or (better) force InvariantCulture: Double.Parse("1.234567E-06", NumberStyles.Float, CultureInfo.InvariantCulture); Commented Jun 10, 2013 at 12:48
  • Note that if you tack a .ToString() on the end of this procedure call it will return the scientific notation and not a string of only digits. I needed to include a format string parameter ("0.0000") in the .ToString() call to make the float format correctly.
    – Eric Ness
    Commented Jan 10, 2014 at 17:34
13

Also consider using

Double.TryParse("1.234567E-06", System.Globalization.NumberStyles.Float, out MyFloat);

This will ensure that MyFloat is set to value 0 if, for whatever reason, the conversion could not be performed. Or you could wrap the Double.Parse() example in a Try..Catch block and set MyFloat to a value of your choosing when an exception is detected.

1
  • 22
    You don't want to rely on MyFloat being 0 to indicate a failed conversion, you want to rely on the bool return value.
    – Carl
    Commented Oct 21, 2008 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.