如何将字符串 3.0E-4 转换为十进制

How to convert the string 3.0E-4 to decimal

我有一个字符串"3.0E-4",它应该是一个十进制数。

请告知如何转换为小数。

你可以使用AllowExponent and AllowDecimalPoint styles combination with decimal.Parse method喜欢;

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

试试这个:

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

或喜欢

decimal x = Decimal.Parse("3.0E-4", NumberStyles.Any, CultureInfo.InvariantCulture);

使用.TryParse避免异常处理(如果解析失败.Parse将抛出异常):

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!");
    }
}

请参阅 here 了解更多信息,了解为什么您应该更喜欢 TryParse。