实现说明
for value in (0.5, 1.5, 2.5, 3.5, -0.5, -2.5) 是唯一的迭代点——其余代码顺序执行一遍。
使用要点
- 直接运行文件,输出会带上标签,比如
round(0.125, 2) ->、round(0.135, 2) ->、round(2.675, 2) ->——输出的每一行都能指回产生它的那次调用。
常见问题
需要标准库之外的东西吗?
除标准库外不引入任何东西——这个示例没有依赖。
核心语句
for value in (0.5, 1.5, 2.5, 3.5, -0.5, -2.5):
print(value, "->", round(value))
代码示例
from decimal import Decimal, ROUND_HALF_UP
# round() uses banker's rounding: it rounds half to even, so an exact .5
# tie goes to the even neighbor instead of always up
for value in (0.5, 1.5, 2.5, 3.5, -0.5, -2.5):
print(value, "->", round(value))
# With a digits argument the same even tie-break applies at that scale
print("round(0.125, 2) ->", round(0.125, 2))
# 0.135 is not a true tie: its binary form sits slightly above, so it rounds up
print("round(0.135, 2) ->", round(0.135, 2))
# Most decimal literals are not exact in binary, so .5 ties are rare there
print("round(2.675, 2) ->", round(2.675, 2))
# When a fixed rounding policy is required, Decimal spells it out exactly
print("Decimal('2.5') half-up ->", Decimal("2.5").quantize(Decimal("1"), rounding=ROUND_HALF_UP))