>我有一个浮点数,想限制为小数点后两位。
我已经尝试了 format(( 和 round((,但仍然只得到 0 或 0.0
x = 8.972990688205408e-05
print ("x: ", x)
print ("x using round():", round(x))
print ("x using format():"+"{:.2f}".format(x))
output:
x: 8.972990688205408e-05
x using round(): 0
x using format():0.00
我期待 8.98 或 8.97,具体取决于使用的方法。我错过了什么?
您使用的是科学记数法。正如 glhr 在评论中指出的那样,您正在尝试四舍五入8.972990688205408e-05 = 0.00008972990688205408
.这意味着尝试四舍五入为浮点类型将只打印小数点后的前两个0
,从而导致0.00
。您必须通过以下方式格式化 0:.2e
:
x = 8.972990688205408e-05
print("{0:.2e}".format(x))
这将打印:
8.97e-05
您在一条评论中询问了如何仅获得 8.97。这是这样做的方法:
y = x*1e+05
print("{0:.2f}".format(y))
输出:
8.97
在python(和许多其他编程语言(中,任何带有e
的数字后缀与数字,它是10的幂与数字。
例如
8.9729e05 = 8.9729 x 10^3 = 8972.9
8.9729e-05 = 8.9729 x 10^-3 = 0.000089729
8.9729e0 = 8.9729 x 10^0 = 8.9729
8.972990688205408e-05 8.972990688205408 x 10^-5 = 0.00008972990688205408
8.9729e # invalid syntax
正如其他答案所指出的,如果你想打印出指数四舍五入,你需要使用正确的Python字符串格式,你有很多选择可供选择。
e Floating point exponential format (lowercase, precision default to 6 digit)
e Floating point exponential format (uppercase, precision default to 6 digit).
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise
例如
x = 8.972990688205408e-05
print('{:e}'.format(x)) # 8.972991e-05
print('{:E}'.format(x)) # 8.972991E-05
print('{:.2e}'.format(x)) # 8.97e-05
(更新(
OP 询问了一种删除指数"E"数字的方法。由于 str.format(( 或 "%" 表示法只输出一个字符串对象,因此将 "e" 表示法从字符串中分离出来就可以了。
'{:.2e}'.format(x).split("e") # ['8.97', '-05']
print('{:.2e}'.format(x).split('e')[0]) # 8.97
如果我理解正确,你只想四舍五入尾数/有效数?如果要将x
保留为float
并输出float
,只需在调用round
时指定精度:
x = round(8.972990688205408e-05,7)
输出:
8.97e-05
但是,我建议先使用 decimal
模块转换x
,该模块"支持快速正确舍入的十进制浮点运算"(请参阅此答案(:
from decimal import Decimal
x = Decimal('8.972990688205408e-05').quantize(Decimal('1e-7')) # output: 0.0000897
print('%.2E' % x)
输出:
8.97E-05
或者使用 format
方法的缩写形式,它给出相同的输出:
print(f"{x:.2E}")
rount() returns closest multiple of 10 to the power minus ndigits,
所以你没有机会得到8.98或8.97。 你也可以在这里查看。