Search code examples
c#decimalformatexception

Decimal.Parse throws a FormatException


I tried to use the decimal.parse as described at : http://msdn.microsoft.com/en-us/library/cafs243z(v=vs.110).aspx

So i copied from this page the following example:

   string value;
   decimal number;
   value = "1.62345e-02";
   try
   {
       number = Decimal.Parse(value);
       Console.WriteLine("'{0}' converted to {1}.", value, number);
   }
   catch (FormatException)
   {
       Console.WriteLine("Unable to parse '{0}'.", value);
   }

And i got a FormatException, Do you have an idea why it's happened?

thanks, eyal


Solution

  • Try this:

    using System.Globalization;
    using System.Text;
    
    ....
    
    number = Decimal.Parse(value, NumberStyles.AllowExponent|NumberStyles.AllowDecimalPoint);
    

    In order to parse a number in exponential format, you need to set the appropriate flags from NumberStyles Enumeration as described here.