Convert numbers with exponential notation from string to double or decimal

后端 未结 4 841
栀梦
栀梦 2020-12-11 01:28

Is there a fast way to convert numbers with exponential notation (examples: \"0.5e10\" or \"-5e20\") to decimal or double?

Update: I found Parse a N

相关标签:
4条回答
  • 2020-12-11 01:44

    If your culture uses . as the decimal separator, just double.Parse("1.50E-15") should work.

    If your culture uses something else (e.g. ,) or you want to make sure your application works the same on every computer, you should use InvariantCulture:

    double.Parse("1.50E-15", CultureInfo.InvariantCulture)
    
    0 讨论(0)
  • 2020-12-11 01:49

    the Math.Round does it well, it will reder the number so that will remove, here is how to use it:

    Math.Round(Double.Parse("3,55E-15"),2)
    
    0 讨论(0)
  • 2020-12-11 01:51

    The standard double.Parse or decimal.Parse methods do the job here.

    Examples:

    // AllowExponent is implicit
    var number1 = double.Parse("0.5e10");
    Debug.Assert(number1 == 5000000000.0);
    
    // AllowExponent must be given explicitly
    var number2 = decimal.Parse("0.5e10", NumberStyles.AllowExponent);
    Debug.Assert(number2 == 5000000000m);
    

    Also, see the MSDN article Parsing Numeric Strings for more information. As long as the NumberStyles.AllowExponent option is specified to the Parse method (which it is by default for double), parsing such strings will work fine.

    NB: As the questioner points out, the exponential notation of "e10" for example does not work in all cultures. Specifying en-US culture however ensures that it works. I suspect CultureInfo.InvariantCulture should also do the trick.

    0 讨论(0)
  • 2020-12-11 01:53

    @Noldorin is correct try this code:

    string str = "-5e20";
    double d = double.Parse(str);
    Console.WriteLine(str);
    
    0 讨论(0)
提交回复
热议问题