tau
tau

Reputation: 6749

Parsing decimal in scientific notation

I'm a bit confused as to why NumberStyles.AllowExponent alone does not parse my decimal in scientific notation.

This throws an exception:

Decimal.Parse("4.06396113432292E-08",
    System.Globalization.NumberStyles.AllowExponent)

This, however, does not:

Decimal.Parse("4.06396113432292E-08",
    System.Globalization.NumberStyles.AllowExponent
    | System.Globalization.NumberStyles.Float)

I don't see what NumberStyle.Float adds (I didn't understand the MSDN documentation on it).

Upvotes: 5

Views: 1976

Answers (3)

Aung Kaung Hein
Aung Kaung Hein

Reputation: 1566

System.Globalization.NumberStyles.AllowExponent allows the parsed string to contain an exponent that begins with the "E" or "e" character.

To allow a decimal separator or sign in the significand or mantissa, you have to use System.Globalization.NumberStyles.Float.

Upvotes: 3

Alex R.
Alex R.

Reputation: 4754

Note from MSDN: AllowExponent

It does not allow a decimal separator or sign in the significand or mantissa; to allow these elements in the string to be parsed, use the AllowDecimalPoint and AllowLeadingSign flags, or use a composite style that includes these individual flags.

Upvotes: 2

Blorgbeard
Blorgbeard

Reputation: 103467

From MSDN:

NumberStyle.Float
Indicates that the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowDecimalPoint, and AllowExponent styles are used. This is a composite number style.

If you don't allow a decimal point, 4.06... won't parse.

Note that NumberStyle.Float also includes AllowExponent, so you don't need to specify that separately. This should work by itself:

Decimal.Parse("4.06396113432292E-08", System.Globalization.NumberStyles.Float)

Upvotes: 5

Related Questions