· 1 min read

Banker's rounding: why Python and Excel disagree

Python rounds halves to the nearest even number while Excel rounds them away from zero, so the same value can give different results.

evergreenpythonlearning

What I learned#

Python’s round() uses banker’s rounding: when a number sits exactly halfway, it goes to the nearest even number. Excel rounds halves away from zero, the way most of us learned in school.

round(0.5)  # 0
round(1.5)  # 2
round(2.5)  # 2
round(3.5)  # 4

In Excel, =ROUND(2.5, 0) gives 3.

Decimals add a second trap. round(2.675, 2) returns 2.67 in Python, while Excel returns 2.68. The reason is that the float 2.675 is stored as a value slightly below 2.675, so it is not a true halfway case.

For school-style rounding, use Decimal with ROUND_HALF_UP. The 0.01 only sets the number of decimal places. What you pass in matters: a string keeps 2.675 exact, while a float brings its error along.

from decimal import Decimal, ROUND_HALF_UP

q = Decimal("0.01")
Decimal("2.675").quantize(q, rounding=ROUND_HALF_UP)  # 2.68 (string)
Decimal(2.675).quantize(q, rounding=ROUND_HALF_UP)    # 2.67 (float)
Decimal("2.5").quantize(Decimal("1"), rounding=ROUND_HALF_UP)  # 3 (string)

The float version holds 2.67499999999999982236..., which is why it rounds down.

Why it matters#

Always rounding halves up makes a big pile of numbers drift upward. Rounding to even makes the errors cancel out. But if you compare a Python report with an Excel sheet, totals can differ by a few cents and neither side has a bug. For money, use Decimal and pick the rounding rule on purpose.