我希望a四舍五入到13.95。我试过用圆形,但我得到:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。
我希望a四舍五入到13.95。我试过用圆形,但我得到:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。
当前回答
请尝试以下代码:
>>> a = 0.99334
>>> a = int((a * 100) + 0.5) / 100.0 # Adding 0.5 rounds it up
>>> print a
0.99
其他回答
在Python中,可以使用格式运算符将值舍入到两位小数:
print(format(14.4499923, '.2f')) // The output is 14.45
它正按照您的指示执行,并且工作正常。阅读更多关于浮点混淆的内容,并尝试使用十进制对象。
Use
print"{:.2f}".format(a)
而不是
print"{0:.2f}".format(a)
因为后者在尝试输出多个变量时可能会导致输出错误(请参见注释)。
您可以修改输出格式:
>>> a = 13.95
>>> a
13.949999999999999
>>> print "%.2f" % a
13.95
lambda x, n:int(x*10^n + 0.5)/10^n
他为我工作了很多年,精通多种语言。