Question

This is probably an old one but I can't find anything on it. Does anyone have any idea why this:

Convert.ToDecimal("3.14521963414679E-08")

throws

FormatException ("Input string was not in a correct format.")

However this works as expected?

Convert.ToDouble("3.14521963414679E-08")

I thought Convert.ToDecimal could handle exponentials - maybe I got that wrong.

Was it helpful?

Solution

Convert.ToDecimal doesn't support the scientific notation.

It is documented that Convert.ToDecimal internally uses Decimal.Parse and the documentation for Decimal.Parse states that this uses NumberStyles.Number and thus only the following is a valid input:

[ws][sign][digits,]digits[.fractional-digits][ws] 

To support scientific notation you will have to use another overload of Decimal.Parse that allows you to specify the NumberStyles to be used:

var result = decimal.Parse("3.14521963414679E-08",
                           NumberStyles.Number | NumberStyles.AllowExponent);

OTHER TIPS

Convert.ToDecimal() method uses Decimal.Parse() explicitly.

From MSDN;

Indicates that the numeric string can be in exponential notation. The AllowExponent flag allows the parsed string to contain an exponent that begins with the "E" or "e" character and that is followed by an optional positive or negative sign and an integer. In other words, it successfully parses strings in the form nnnExx, nnnE+xx, and nnnE-xx. 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.

You can use Decimal.Parse Method (String, NumberStyles) overload of this method which allows you to use NumberStyles enumration like;

Decimal.Parse("3.14521963414679E-08",
              NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint);

Here a DEMO.

Because of this->

ToDecimal(String)--Converts the specified string representation of a number to an equivalent decimal number..

ToDouble(String)--Converts the specified string representation of a number to an equivalent double-precision floating-point number.

for further clarification visit- http://msdn.microsoft.com/en-us/library/System.Convert_methods.aspx

Hope it helps..:)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top