4

I have a string "3.0E-4", it is supposed to be a decimal number.

Please advise how to convert to a decimal.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
khoailang
  • 725
  • 1
  • 15
  • 32

3 Answers3

7

You can use AllowExponent and AllowDecimalPoint styles combination with decimal.Parse method like;

var result = decimal.Parse("3.0E-4", 
                           NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint, 
                           CultureInfo.InvariantCulture);

enter image description here

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • thanks, this looks obsoleted, I don't see an overload with CultureInfo. – khoailang Oct 30 '15 at 13:57
  • 2
    @khoailang Obsolete o.O? It is _definitely_ not and [`Decimal.Parse(String, NumberStyles, IFormatProvider)`](https://msdn.microsoft.com/en-us/library/s84kdbzx.aspx) overload exist since .NET 2.0. Are you _really_ sure about that? What is your environment? – Soner Gönül Oct 30 '15 at 14:03
3

Try this:

decimal x = Decimal.Parse("3.0E-4", NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint);

or like

decimal x = Decimal.Parse("3.0E-4", NumberStyles.Any, CultureInfo.InvariantCulture);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

Using .TryParse avoids exception handling (.Parse will throw and exception if parsing fails):

void Main()
{
    var str="3.0E-4";
    float d;
    if (float.TryParse(str, out d))
    {
        Console.WriteLine("d = " + d.ToString());
    }
    else
    {
        Console.WriteLine("Not a valid decimal!");
    }
}

enter image description here

See here for more info why you should prefer TryParse.

Community
  • 1
  • 1
Matt
  • 25,467
  • 18
  • 120
  • 187
  • thanks, I tried this with the decimal, can not parse the string, the tryparse returns false! – khoailang Oct 30 '15 at 13:56
  • Right, you have to use `float`. For me, `decimal` was not working as well - that's why I posted this. @khoailang – Matt Oct 30 '15 at 14:27