I have a string "3.0E-4"
, it is supposed to be a decimal number.
Please advise how to convert to a decimal.
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);
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);
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!");
}
}
See here for more info why you should prefer TryParse.