19

Is there a fast way to convert numbers with exponential notation (examples: "0.5e10" or "-5e20") to decimal or double?

Update: I found Parse a Number from Exponential Notation but the examples won't work for me unless I specified a culture.

Solution:

double test = double.Parse("1.50E-15", CultureInfo.InvariantCulture);
Community
  • 1
  • 1
OMGKurtNilsen
  • 5,048
  • 7
  • 27
  • 36
  • You can use the following: http://msdn.microsoft.com/en-us/library/system.math.exp.aspx – Security Hound Oct 24 '11 at 15:18
  • @Ramhound: That's non-ideal for a number of reasons; not to mention is use expensive floating-point operations, is unnecessarily convoluted, and is designed for a much more general x ^ y operation where x and y are both reals. – Noldorin Oct 24 '11 at 15:20
  • Have you tryied double.TryParse and decimal.TryParse? – Emmanuel N Oct 24 '11 at 15:22

4 Answers4

22

If your culture uses . as the decimal separator, just double.Parse("1.50E-15") should work.

If your culture uses something else (e.g. ,) or you want to make sure your application works the same on every computer, you should use InvariantCulture:

double.Parse("1.50E-15", CultureInfo.InvariantCulture)
svick
  • 236,525
  • 50
  • 385
  • 514
10

The standard double.Parse or decimal.Parse methods do the job here.

Examples:

// AllowExponent is implicit
var number1 = double.Parse("0.5e10");
Debug.Assert(number1 == 5000000000.0);

// AllowExponent must be given explicitly
var number2 = decimal.Parse("0.5e10", NumberStyles.AllowExponent);
Debug.Assert(number2 == 5000000000m);

Also, see the MSDN article Parsing Numeric Strings for more information. As long as the NumberStyles.AllowExponent option is specified to the Parse method (which it is by default for double), parsing such strings will work fine.

NB: As the questioner points out, the exponential notation of "e10" for example does not work in all cultures. Specifying en-US culture however ensures that it works. I suspect CultureInfo.InvariantCulture should also do the trick.

Noldorin
  • 144,213
  • 56
  • 264
  • 302
2

@Noldorin is correct try this code:

string str = "-5e20";
double d = double.Parse(str);
Console.WriteLine(str);
Kevin Holditch
  • 5,165
  • 3
  • 19
  • 35
  • 2
    Thanks for confirming. This should probably belong as a comment though, as it's just re-iterating what I've done. :-) – Noldorin Oct 24 '11 at 15:28
  • I know I did originally add as comment but then realised you couldnt put a code block in a comment – Kevin Holditch Oct 24 '11 at 15:29
  • No worries. Feel free to edit my answer, after all (you have the privelege at your rep yes?). If not, the example is there now. We probably added them at the same time. – Noldorin Oct 24 '11 at 15:30
1

the Math.Round does it well, it will reder the number so that will remove, here is how to use it:

Math.Round(Double.Parse("3,55E-15"),2)
Tshilidzi Mudau
  • 7,373
  • 6
  • 36
  • 49
KARIM Yassine
  • 143
  • 1
  • 11