views:

112

answers:

4

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

A: 

Try parsing it as a double, then cast to decimal.

If doesn't work, roll-your-own parser?

Daniel Mošmondor
+3  A: 

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

decimal d = Decimal.Parse("1.2345E-02", System.Globalization.NumberStyles.Float);
Hans Passant
+2  A: 

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.

Jon Skeet
+1  A: 
    static void Main(string[] args)
    {
        decimal d = Decimal.Parse("1.2345E-02",
                                  System.Globalization.NumberStyles.Float);

    }
Mitch Wheat