Frage

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

War es hilfreich?

Lösung 2

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.

Andere Tipps

shree.pat18's answer is of course right. But I want to explain this question a little bit more if you let me..

Let's look at how Decimal.ToParse(string) method implemented;

public static Decimal Parse(String s)
{
   return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo);
}

As you can see, this method uses NumberStyles.Number by default. It is a composite number style and it's implemented like;

Number   = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
           AllowDecimalPoint | AllowThousands,

That means your string can have one of;

Since NumberStyles.Number has AllowDecimalPoint, it fits . in your string but this style doesn't have AllowExponent that's why it can't parse e-02 in your string.

That's why you need to use Decimal.Parse Method (String, NumberStyles) overload since you can specify NumberStyles yourself.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top