round() Rounds Half To Even, Not Always Up

round() breaks exact .5 ties toward the even neighbor while binary float storage decides the rest; printed results show both, plus the Decimal escape hatch.

PythonData Integrity

Code

pythonsnippet
18 lines
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))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How it works

Iteration happens inside for value in (0.5, 1.5, 2.5, 3.5, -0.5, -2.5) — everything outside it runs once.

Caveats

  • Entirely standard-library — copy it in and it runs.

Applying it

Look for the round(0.125, 2) ->, round(0.135, 2) ->, round(2.675, 2) -> prefixes when the file runs; they tie each line to its step.

Statements that matter

for value in (0.5, 1.5, 2.5, 3.5, -0.5, -2.5):
    print(value, "->", round(value))

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free.