Hone

Lessons · Python · round() sends halves to even

Rounding halves to even

round() sends an exact .5 to the nearest even number: round(2.5) is 2 and round(3.5) is 4. The errors cancel over a long column.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Financial and scientific totals are rounded thousands of times; always rounding halves up would bias every total upward. Banker's rounding keeps the sum honest.

How to think about it

Expect .5 to go to the even neighbour, and remember most decimals are not exact in binary, so round(2.675, 2) can surprise you too. For money, use Decimal with an explicit rounding mode.

Worked example

print(round(2.5), round(3.5))
2 4: each half goes to the even side.
print(round(0.5), round(1.5))
0 2.
print(round(2.675, 2))
2.67: the stored value is slightly below 2.675, so it was never a true half.
from decimal import Decimal, ROUND_HALF_UP
The explicit rule.
print(Decimal("2.5").quantize(Decimal("1"), rounding=ROUND_HALF_UP))
3: when you must round halves up, say so.

Your turn

Round a Decimal to whole units, halves up.

Decimal("2.5").quantize(Decimal("1"), rounding=)

The trap

int(x + 0.5) as a rounding trick fails for negatives and for large floats. Use round, or Decimal when the rule matters.

Practise round() sends halves to even on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.