我希望a四舍五入到13.95。我试过用圆形,但我得到:

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999

有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。


当前回答

我们有多种选择:

选项1:

x = 1.090675765757
g = float("{:.2f}".format(x))
print(g)

选项2:内置round()支持Python 2.7或更高版本。

x = 1.090675765757
g = round(x, 2)
print(g)

其他回答

在Python 2.7中:

a = 13.949999999999999
output = float("%0.2f"%a)
print output

Use

print"{:.2f}".format(a)

而不是

print"{0:.2f}".format(a)

因为后者在尝试输出多个变量时可能会导致输出错误(请参见注释)。

内置round()在Python 2.7或更高版本中运行良好。

例子:

>>> round(14.22222223, 2)
14.22

查看文档。

请尝试以下代码:

>>> a = 0.99334
>>> a = int((a * 100) + 0.5) / 100.0 # Adding 0.5 rounds it up
>>> print a
0.99

简单的解决方案在这里

value = 5.34343
rounded_value = round(value, 2) # 5.34