Skip to content

Integer division truncation bug

Quick summary

You used // and got an unexpected result because floor division rounds toward negative infinity, not toward zero like truncation.

Why this happens

  • You expected // to truncate toward zero (like C/Java) but Python floor division rounds toward negative infinity

  • The division involves negative numbers where floor division and truncation give different results

  • You used // for floating-point division and got an unexpected float result instead of an integer

Minimal example

✗ Broken code
result = -7 // 2  # expected -3 (truncation), got -4 (floor)
print(result)  # -4
✓ Fixed code
import math
result = math.trunc(-7 / 2)  # truncation toward zero
print(result)  # -3

math.trunc() rounds toward zero giving -3, while // floors toward negative infinity giving -4 for -7 // 2.

How to diagnose

  • Print the result of the division and compare with the expected value, especially for negative operands

  • Use math.trunc(a / b) instead of a // b if you want truncation toward zero

  • Check whether the operands can be negative and test the division with both positive and negative values

How to fix

  • Use int(a / b) or math.trunc(a / b) for truncation toward zero instead of floor division

  • Use math.ceil(a / b) or math.floor(a / b) explicitly if you need a specific rounding direction

  • Use / for true division (returns float) and int() to convert if you want integer truncation toward zero

How to prevent

  • Understand that Python // is floor division (rounds toward -inf), not truncation (rounds toward 0)

  • Test division operations with negative numbers to catch floor vs truncation discrepancies early

Related Resources

Related Glossary

Related Lessons

← Back to language