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
views:
112answers:
4
A:
Try parsing it as a double, then cast to decimal.
If doesn't work, roll-your-own parser?
Daniel Mošmondor
2010-10-07 07:21:20
+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
2010-10-07 07:22:21
+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
2010-10-07 07:23:50
+1
A:
static void Main(string[] args)
{
decimal d = Decimal.Parse("1.2345E-02",
System.Globalization.NumberStyles.Float);
}
Mitch Wheat
2010-10-07 07:24:36