Convert numbers with exponential notation from string to double or decimal

送分小仙女□ 提交于 2019-11-27 06:39:18

问题


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 Number from Exponential Notation but the examples won't work for me unless I specified a culture.

Solution:

double test = double.Parse("1.50E-15", CultureInfo.InvariantCulture);

回答1:


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)



回答2:


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.




回答3:


@Noldorin is correct try this code:

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



回答4:


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)


来源:https://stackoverflow.com/questions/7877855/convert-numbers-with-exponential-notation-from-string-to-double-or-decimal

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