[英]Scientific notation not working in python
我正在使用 python 版本3.9.5
,并尝试使用format
方法使用科学记数法,但它不起作用!
我已经在 web 中搜索了这个,但没有得到任何东西。
我用format(num, f'.{precision}e')
的格式化方法把它转成科学计数法,对非小数有效,但是当我用小数时,就不行了:
num = int(10**9) # 1000000000
dec = int(10**-4) # 0.0001
print(format(num, '.5e'))
print(format(dec, '.5e'))
# 1.00000e+09
# 0.00000e+00
如您所见,第二个 output 本来是不同的结果,但我得到了0.00000e+00
有人可以帮我解决这个问题吗,在此先感谢。
int(x)
永远是 integer。
print(int(10**-4))
#output
0
你需要做:
print(format(float(10**-4), '.5e'))
#output
1.00000e-04
在 Python 3.9 中,您可以使用 f 前缀和 {:e} 格式说明符以科学计数法格式化数字。 这是一个例子:
x = 12345.678
print(f"{x:e}") # prints 1.234568e+04
如果要指定小数位数,可以使用 .nf 语法,其中 n 是小数位数。 例如:
x = 12345.678
print(f"{x:.2e}") # prints 1.23e+04
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.