Convert numbers with exponential notation from string to double or decimal

筅森魡賤 提交于 2019-11-28 11:58:51

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)

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.

@Noldorin is correct try this code:

string str = "-5e20";
double d = double.Parse(str);
Console.WriteLine(str);
KARIM Yassine

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!