Search code examples
c#bigdecimal

How to parse a string that contains E- notation into decimal


I'd like to return convert string to decimal, but few rows are throwing exception (see code below).

Func<DataRow, string, decimal?> getFieldNullableDecimal = (row, field) =>
{
   if (!string.IsNullOrWhiteSpace((row[field] ?? string.Empty).ToString()))
   {
      var data = row[field].ToString();
      return decimal.Parse(data);           //--this line is throwing exception
   }
 }

The error is being thrown when the value returned by the database is of the following form: -2.8421709430404E-14

What I thinking of doing is just to check whether the string as "E-". I'll then convert both parts in number then multiply them. However, before I do that, I'd like to know whether there exists a method that already does it.

Thanks for helping


Solution

  • You need to use NumberStyles.AllowExponent and NumberStyles.Float. For example:

    Decimal.Parse("-2.8421709430404E-14", 
                  NumberStyles.AllowExponent | NumberStyles.Float);
    

    Something like this:

    if (!string.IsNullOrWhiteSpace((row[field] ?? string.Empty).ToString()))
    {
        return decimal.Parse(row[field].ToString(), 
                             NumberStyles.AllowExponent | NumberStyles.Float);
    }
    

    Please note, this assumes you have the System.Globalization namespace in your using statements. For example:

    using System.Globalization;
    

    Alternatively, as John Skeet is point out, you should not need to convert it to a string and then to decimal.

    If it is a Float in the database, the equivalent in the CLR is Double. So you could just try and cast it to a Double. For example:

    return (double)row[field];