Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 512
tau Avatar asked Dec 26 '22 12:12

tau


2 Answers

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)
like image 181
Blorgbeard Avatar answered Jan 01 '23 18:01

Blorgbeard


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.

like image 25
Aung Kaung Hein Avatar answered Jan 01 '23 16:01

Aung Kaung Hein