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

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

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


当前回答

lambda x, n:int(x*10^n + 0.5)/10^n

他为我工作了很多年,精通多种语言。

其他回答

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

例子:

>>> round(14.22222223, 2)
14.22

查看文档。

orig_float = 232569 / 16000.0

14.5355625

short_float = float("{:.2f}".format(orig_float)) 

14.54

使用如下lambda函数:

arred = lambda x,n : x*(10**n)//1/(10**n)

这样你就可以:

arred(3.141591657, 2)

然后得到

3.14

简单的解决方案在这里

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

正如Matt所指出的,Python 3.6提供了f字符串,它们也可以使用嵌套参数:

value = 2.34558
precision = 2
width = 4

print(f'result: {value:{width}.{precision}f}')

显示结果:2.35