Python 将科学记数法转换为小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29849445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert scientific notation to decimals
提问by user3223818
I have numbers in a file (so, as strings) in scientific notation, like:
我在文件中有数字(所以,作为字符串)以科学记数法表示,例如:
8.99284722486562e-02
but I want to convert them to:
但我想将它们转换为:
0.08992847
Is there any built-in function or any other way to do it?
是否有任何内置功能或任何其他方式来做到这一点?
回答by m0dem
I'm pretty sure you can do this with:
我很确定你可以这样做:
float("8.99284722486562e-02")
# and now with 'rounding'
"{:.8f}".format(float("8.99284722486562e-02"))
回答by jesterjunk
The scientific notation can be converted to a floating point number with float
.
可以使用 将科学记数法转换为浮点数float
。
? ?In [1]: ?float("8.99284722486562e-02")
Out [1]: ? 0.0899284722486562
? ?在[1]中:float("8.99284722486562e-02")
出[1]:?0.0899284722486562
The float
can be rounded with format
and then float
can be used on the string to return the final rounded float.
该float
可以用圆润format
,然后float
可以在字符串中使用返回最终圆浮动。
? ?In [2]: ?float("{:.8f}".format(float("8.99284722486562e-02")))
Out [2]: ? 0.08992847
? ?在[2]中:float("{:.8f}".format(float("8.99284722486562e-02")))
出[2]:?0.08992847
回答by User
As you may know floating point numbers have precision problems. For example, evaluate:
您可能知道浮点数存在精度问题。例如,评估:
>>> (0.1 + 0.1 + 0.1) == 0.3
False
Instead you may want to use the Decimalclass. At the python interpreter:
相反,您可能想要使用Decimal类。在 python 解释器中:
>>> import decimal
>>> tmp = decimal.Decimal('8.99284722486562e-02')
Decimal('0.0899284722486562')
>>> decimal.getcontext().prec = 7
>>> decimal.getcontext().create_decimal(tmp)
Decimal('0.08992847')