Search code examples
c#type-conversiondecimaldata-conversionscientific-notation

How to Convert Positive or Negative Scientific Notation to Number in C#?


I have tried this two codes:

1)

Decimal h2 = 0;
Decimal.TryParse("-8.13E-06", out h2);

2)

Decimal.Parse(Convert.ToString(used[row, column].Value), NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint); 

But It is not working for -8.13E-06 Value.

Any other better option to convert Scientific Notation to Decimal?

Thanks in Advance.


Solution

  • If your culture uses "." as separator:

    decimal d = Decimal.Parse("-8.13E-06", System.Globalization.NumberStyles.Float);
    

    Or you can specify the InvariantCulture:

    decimal d = Decimal.Parse("-8.13E-06", System.Globalization.NumberStyles.Float, CultureInfo.InvariantCulture);
    

    or as in your exapmple:

    Decimal h2 = 0;
    Decimal.TryParse("-8.13E-06", NumberStyles.Float, CultureInfo.InvariantCulture, out h2);