Monday, September 15, 2008

Scientific Notation to Decimal

I recently had a situation come up where I needed to convert numeric data that was in scientific notation to a decimal. As an example I would receive a string that was in the form 1E-9. The decimal representation of this is 0.000000001. Seems simple enough.

string sVal = "1E-9";
decimal val = Convert.ToDecimal(sVal);

The above code fails because ToDecimal uses NumberStyles.Number which doesn't include the AllowExponent switch. You'll receive a FormatException exception that states the input string was not in a correct format. Use the following to convert to a decimal.

string sVal = "1E-9";
decimal val = 0M;

if(!Decimal.TryParse(sVal, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out val))
val = 0M;


No comments: