Python traps · Python
Python: round(2.5) = 2?!FREE
Python rounds exact halves to the nearest EVEN number. See it happen, then use school rounding when you need it.
# round(2.5) = 2 ?! — Python rounds exact halves to the nearest EVEN number
# ("banker's rounding"), so ties don't all drift upwards.
print("round(2.5) =", round(2.5)) # 2 ?!
print("round(3.5) =", round(3.5)) # 4
print("round(0.5) =", round(0.5)) # 0
print("round(1.5) =", round(1.5)) # 2
# School rounding (halves always go up) for positive numbers:
def school_round(x):
return int(x + 0.5)
print("school_round(2.5) =", school_round(2.5)) # 3 ✓
# Try it: change 2.5 to 2.51 — no longer a tie, so it rounds to 3.
+ 1 more lines in the app
Open code P1 in Pocket Compiler
Download the Pocket Compiler app — free
No app yet? Install it, then open the app and type the code P1 in Code Library.