Convert scientific notation to decimals

拈花ヽ惹草 提交于 2019-11-29 12:36:35

问题


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?


回答1:


I'm pretty sure you can do this with:

float("8.99284722486562e-02")
# and now with 'rounding'
"{:.8f}".format(float("8.99284722486562e-02"))



回答2:


The scientific notation can be converted to a floating point number with float.

   In [1]:  float("8.99284722486562e-02")
Out [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.

   In [2]:  float("{:.8f}".format(float("8.99284722486562e-02")))
Out [2]:   0.08992847




回答3:


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 Decimal class. At the python interpreter:

>>> import decimal
>>> tmp = decimal.Decimal('8.99284722486562e-02')
Decimal('0.0899284722486562')
>>> decimal.getcontext().prec = 7
>>> decimal.getcontext().create_decimal(tmp)
Decimal('0.08992847')


来源:https://stackoverflow.com/questions/29849445/convert-scientific-notation-to-decimals

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