TryBugHunt

round(2.5) returns 2

round(2.5) returns 2 in Python means python's round() uses round-half-to-even: an exact .5 goes to the nearest even number, so 2.5 becomes 2 and 3.5 becomes 4.

PythonPattern: Logic errors

How do I fix round(2.5) returns 2?

Python's round(2.5) returns 2 because round() uses round-half-to-even, also called banker's rounding. An exact .5 goes to the nearest even number, so 3.5 becomes 4. For school-style rounding, use decimal: Decimal("2.5").quantize(Decimal("1"), rounding=ROUND_HALF_UP). Build the Decimal from a string, not a float.

  1. 1. Only exact halvesTest values like 0.5, 2.5 and 4.5. Other numbers round as expected, so most tests pass.
  2. 2. Use ROUND_HALF_UPFor grades, prices and tax, use Decimal(...).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP).
  3. 3. Float storage errorround(2.675, 2) gives 2.67 because 2.675 is stored slightly lower. Create Decimal("2.675") from a string.

What does round(2.5) returns 2 mean?

Always rounding .5 up creates an upward bias when you round many numbers; rounding halves to the even neighbour cancels it out. It is the IEEE 754 default and what statistics wants, but not the rule taught in school, so marks, prices and receipts can come out one lower than expected.

Why does round(2.5) returns 2 happen?

1. Expecting school rounding

Only exact halves are affected, so most tests pass.

Breaks

round(2.5)   # 2

Works

import math
math.floor(2.5 + 0.5)   # 3, for positive numbers

2. Rounding money to cents

Floats add their own error on top: 2.675 is stored just below 2.675.

Breaks

round(2.675, 2)   # 2.67

Works

from decimal import Decimal, ROUND_HALF_UP
Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)   # 2.68

How to find it in your own code

If the rule matters (grades, invoices, tax), say which rule you need and use decimal with ROUND_HALF_UP. Use round() only where unbiased rounding is fine, such as averages and statistics.

Try it: fix this bug

easy

round_order_rating(2.5) returns 2 instead of 3.

def round_order_rating(rating):
    return round(rating)
Open with hintsRuns in your browser. No account needed.

More challenges with this error

Each of these challenges runs into this error. Find the bug and fix it, no install and no account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Related error guides

View all logic errors →