为什么 python 中的 0.500000 舍入不同于使用“%.0f”的 45.500000?

Why round off of 0.500000 in python differs from 45.500000 using '%.0f'?

最近,我在Python 2.7 中学习了字符串格式化的技巧。 我决定玩浮点数。
遇到了一个看起来很尴尬的解决方案,如下所示。

print "%.0f"%45.5000000 #46
print "%.0f"%0.5000000 #0

#Why??

但是

print int(round(45.5000000)) #46
print int(round(0.5000000)) #1

请帮助我理解为什么 %f 会出现这种行为。

%.0f 字符串格式的内部实现使用 round-half-even 舍入模式。

在Python 2中,round() function uses round-away-from-zero. In Python 3, that was changed进行四舍五入,使其与字符串格式一致。

FWIW,decimal module offers you a choice of rounding modes if you want more control than afforded by round() or by string formatting. The decimal rounding modes 是:ROUND_05UP ROUND_CEILING ROUND_DOWN ROUND_FLOOR ROUND_HALF_DOWN ROUND_HALF_EVEN ROUND_HALF_UP ROUND_UP。