首页 > 解决方案 > 试图在浮点数上得到两个小数点,但不断得到 0.0

问题描述

我有一个浮点数,想限制为两位小数。

我尝试了 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,具体取决于使用的方法。我错过了什么?

标签: python-3.x

解决方案


您正在使用科学计数法。正如 glhr 在评论中指出的那样,您正在尝试舍入8.972990688205408e-05 = 0.00008972990688205408. 这意味着尝试四舍五入为 float 类型只会打印0小数点后的前两个 s,从而导致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

推荐阅读