round() Rounds Half To Even, Not Always Up
round() breaks exact .5 ties toward the even neighbor while binary float storage decides the rest; printed results show both, plus the Decimal escape hatch.
Code
from decimal import Decimal, ROUND_HALF_UP
# round() uses banker's rounding: it rounds half to even, so an exact .5
# tie goes to the even neighbor instead of always up
for value in (0.5, 1.5, 2.5, 3.5, -0.5, -2.5):
print(value, "->", round(value))
# With a digits argument the same even tie-break applies at that scale
print("round(0.125, 2) ->", round(0.125, 2))
# 0.135 is not a true tie: its binary form sits slightly above, so it rounds up
print("round(0.135, 2) ->", round(0.135, 2))
# Most decimal literals are not exact in binary, so .5 ties are rare there
print("round(2.675, 2) ->", round(2.675, 2))
# When a fixed rounding policy is required, Decimal spells it out exactly
print("Decimal('2.5') half-up ->", Decimal("2.5").quantize(Decimal("1"), rounding=ROUND_HALF_UP))Output
Captured from a sandboxed run of this snippet in the build pipeline.
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4
-0.5 -> 0
-2.5 -> -2
round(0.125, 2) -> 0.12
round(0.135, 2) -> 0.14
round(2.675, 2) -> 2.67
Decimal('2.5') half-up -> 3How it works
Iteration happens inside for value in (0.5, 1.5, 2.5, 3.5, -0.5, -2.5) — everything outside it runs once.
Caveats
- Entirely standard-library — copy it in and it runs.
Applying it
Look for the round(0.125, 2) ->, round(0.135, 2) ->, round(2.675, 2) -> prefixes when the file runs; they tie each line to its step.
Statements that matter
for value in (0.5, 1.5, 2.5, 3.5, -0.5, -2.5):
print(value, "->", round(value))
Interactive Tools for This Topic
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Roman Numeral ConverterConvert integers between 1 and 3999 to Roman numerals and back, rejecting malformed numeral forms.Scientific Notation ConverterConvert numbers between plain decimal and scientific notation, optionally fixing the significant digits and splitting out the mantissa and exponent.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free.
Report a problem with this exampleOpens a pre-filled issue on GitHub.