← 中文资源

简体中文版本

round() 平局舍入到偶数一侧

round() 对恰好 .5 的平局舍入到偶数一侧,其余结果由二进制浮点表示决定;打印结果同时展示两种行为,并给出 Decimal 的显式策略。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4
-0.5 -> 0
-2.5 -> -2
round(0.125, 2) -> 0.12
round(0.135, 2) -> 0.14
round(2.675, 2) -> 2.67
Decimal('2.5') half-up -> 3

实现说明

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))