我有一个文件,里面有科学计数法表示的数字(以字符串形式出现),例如:
8.99284722486562e-02
但我想将它们转换为:
0.08992847
是否有内置函数或其他方法可以实现此功能?
我相信你可以用以下方法实现:
float("8.99284722486562e-02")
# and now with 'rounding'
"{:.8f}".format(float("8.99284722486562e-02"))
因为排名最高的回答中存在误导性信息,所以我撰写了这篇答案来解释我的改进。
简而言之:使用("%.17f" % n).rstrip('0').rstrip('.')
默认情况下,如果小数点前有5个或更多个零,Python会采用科学计数法进行格式化。
0.00001
/ 1e-05
格式化为 "1e-05"
。
0.0001
/ 1e-04
格式化为 "0.0001"
。
因此,8.99284722486562e-02
将被格式化为 "0.0899284722486562"
。
更好的例子是 8.99284722486562e-05
。(0.00008992847224866
)
我们可以通过"%f"
轻松地格式化为原始小数位,该格式化方式默认情况下为"%.6f"
。
"%f" % 8.99284722486562e-05
生成 '0.000090'
。
"%f" % 0.01
生成 '0.010000'
。
默认情况下,浮点数会显示最多17位小数。
0.1234567898765432123
- (19位小数的输入)
0.12345678987654321
- (17位小数的输出)
因此,如果我们使用"%.17f" % 8.99284722486562e-02
,我们将得到'0.08992847224865620'
。(注意额外的0)
但是如果我们使用"%.17f" % 0.0001
,我们肯定不想要'0.00010000000000000'
。
要去掉尾随的零,我们可以这样做:("%.17f" % n).rstrip('0').rstrip('.')
(注意,如果数字没有小数部分,我们也会去除小数点)
%f
有对应的几个格式:
%f
显示标准记法
%e
显示科学计数法
%g
显示默认格式(如果有5个或更多的零则使用科学计数法)
float
转换为浮点数。
In [1]: float("8.99284722486562e-02")
Out [1]: 0.0899284722486562
使用format
对float
进行舍入,然后将float
用于字符串以返回最终舍入的浮点数。
In [2]: float("{:.8f}".format(float("8.99284722486562e-02")))
Out [2]: 0.08992847
2022年修改No Sound的评论:
以下解决方案适用于更大的数字。
解决方案1)
import numpy as np
print(np.format_float_positional(1.32456e-12, trim='-'))
print(np.format_float_positional(1.32456e-24, trim='-'))
print(np.format_float_positional(1.32456e12, trim='-'))
print(np.format_float_positional(1.32456e24, trim='-'))
# Output: 0.00000000000132456
# 0.00000000000000000000000132456
# 1324560000000
# 1324560000000000000000000
解决方案2)
与上述相同,只是这次使用一个lambda函数
import numpy as np
pretty_print = lambda x: np.format_float_positional(x, trim="-")
print(pretty_print(1.32456e-12))
print(pretty_print(1.32456e-24))
print(pretty_print(1.32456e12))
print(pretty_print(1.32456e24))
# Output: 0.00000000000132456
# 0.00000000000000000000000132456
# 1324560000000
# 1324560000000000000000000
float("1.32456e-12")
返回 1.32456e-12
。 - No Sound你可能知道浮点数存在精度问题。例如,计算:
>>> (0.1 + 0.1 + 0.1) == 0.3
False
相反,您可能想使用 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')
print("%.8f" %s)
жҲ–print("{0:.8f}".format(s))
еҚіеҸҜгҖӮ - logicfloat('{:.8f}'.format(float("8.99284722486562e-02")))
。 - Malik Brahimi"{:.8f}.format
应为"{:.8f}".format
,缺少一个双引号。 - jesterjunk"{:.{precision}f}".format(float("8.99284722486562e-02"), precision=8)
- zr0gravity7