#29 · Numbers

Find the bug · #29 · Numbers Hard Python

Half rupees round the wrong way

A bill splitter promises to round halves up, but some halves go down.

On this page

The report

Bug report

A bill-splitting app rounds each person’s share to whole rupees, halves going up, as its help page promises. Splitting ₹5 between two gives ₹2 each, but splitting ₹7 gives ₹4 each.

The code

Read it first: what should it do? Then click the line where you think the bug is.

PythonClick the line you think is wrong
def split_amount(total, people):
    """Each person's share in whole rupees, rounding halves up (so 2.5 becomes 3)."""
    return round(total / people)

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
print(split_amount(5, 2))
print(split_amount(7, 2))
print(split_amount(9, 2))

It prints

2
4
4

It should print

3
4
5
Show the answer: the bug, the fix, and how you’d find it

The bug (line 3)

Line 3 uses Python’s built-in round, which rounds halves to the nearest even number (“banker’s rounding”): 2.5 becomes 2, but 3.5 becomes 4. The app promises halves go up. Use Decimal with ROUND_HALF_UP, which is also the right type for money.

The fix

1from decimal import Decimal, ROUND_HALF_UP2 1def split_amount(total, people):2    """Each person's share in whole rupees, rounding halves up (so 2.5 becomes 3)."""3    return round(total / people)5    share = Decimal(total) / Decimal(people)6    return int(share.quantize(Decimal("1"), rounding=ROUND_HALF_UP))

How you’d find it

  1. Reproduce the two reports: 5 ÷ 2 gives 2, 7 ÷ 2 gives 4. Both are exactly .5, yet one goes down and one goes up.
  2. Try more halves: 4.5 gives 4, 5.5 gives 6. They always land on an even number.
  3. That’s Python 3’s round: half to even. Check the docs, then pick the rounding the product actually promised.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

assert split_amount(5, 2) == 3
assert split_amount(9, 2) == 5
assert split_amount(10, 4) == 3
assert split_amount(9, 3) == 3

Where else this bites

  • NumPy’s round and .NET’s Math.Round also round half to even by default.
  • Tax and GST totals, where the rounding rule is set by law.
Your progress stays on this device.