Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a Number from Exponential Notation

I need to parse the string "1.2345E-02" (a number expressed in exponential notation) to a decimal data type, but Decimal.Parse("1.2345E-02") simply throws an error

like image 716
Jimbo Avatar asked Oct 07 '10 07:10

Jimbo


People also ask

How do I get rid of E notation?

(1) Right-click a cell where you want to remove scientific notation, and (2) choose Format Cells… 2. In the Format Cells window, (1) select the Number category, (2) set the number of decimal places to 0, and (3) click OK. Now the scientific notation is removed.

How do you convert an exponent to a number in JavaScript?

To parse and convert exponential values to decimal in JavaScript, we can use the toFixed method. to call toFixed on 4.656657507739E-10 and return a number with 20 decimal places. Therefore, n is 0.00000000046566575077. toFixed can parse numbers that has up to 20 decimal places.


2 Answers

It is a floating point number, you have to tell it that:

decimal d = Decimal.Parse("1.2345E-02", System.Globalization.NumberStyles.Float); 
like image 69
Hans Passant Avatar answered Sep 19 '22 08:09

Hans Passant


It works if you specify NumberStyles.Float:

decimal x = decimal.Parse("1.2345E-02", NumberStyles.Float); Console.WriteLine(x); // Prints 0.012345 

I'm not entirely sure why this isn't supported by default - the default is to use NumberStyles.Number, which uses the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, and AllowThousands styles. Possibly it's performance-related; specifying an exponent is relatively rare, I suppose.

like image 39
Jon Skeet Avatar answered Sep 18 '22 08:09

Jon Skeet