I found that passing to NumberStyles.Float
, in some cases, changes the rules by which the string is processed, and leads to another output from NumberStyles.Number
(the default rules used by decimal.Parse
).
For example, the following code will throw a FormatException
in my machine:
CultureInfo culture = new CultureInfo(""); culture.NumberFormat.NumberDecimalDigits = 2; culture.NumberFormat.NumberDecimalSeparator = "."; culture.NumberFormat.NumberGroupSeparator = ","; Decimal.Parse("1,234.5", NumberStyles.Float, culture);
I would recommend using the NumberStyles.Number | NumberStyles.AllowExponent
input NumberStyles.Number | NumberStyles.AllowExponent
NumberStyles.Number | NumberStyles.AllowExponent
, as this will allow exponential numbers and will process the string according to decimal
rules.
CultureInfo culture = new CultureInfo(""); culture.NumberFormat.NumberDecimalDigits = 2; culture.NumberFormat.NumberDecimalSeparator = "."; culture.NumberFormat.NumberGroupSeparator = ","; Decimal.Parse("1,234.5",NumberStyles.Number | NumberStyles.AllowExponent, culture);
To answer the question about the poster, the correct answer should be:
decimal x = decimal.Parse("1.2345E-02", NumberStyles.Number | NumberStyles.AllowExponent); Console.WriteLine(x);
bastos.sergio Mar 09 '17 at 17:50 2017-03-09 17:50
source share