Search code examples
pythonroundingdivisionnegative-numberinteger-division

In Python, what is a good way to round towards zero in integer division?


1/2

gives

0

as it should. However,

-1/2

gives

-1

, but I want it to round towards 0 (i.e. I want -1/2 to be 0), regardless of whether it's positive or negative. What is the best way to do that?


Solution

  • Do floating point division then convert to an int. No extra modules needed.

    Python 3:

    >>> int(-1 / 2)
    0
    >>> int(-3 / 2)
    -1
    >>> int(1 / 2)
    0
    >>> int(3 / 2)
    1
    

    Python 2:

    >>> int(float(-1) / 2)
    0
    >>> int(float(-3) / 2)
    -1
    >>> int(float(1) / 2)
    0
    >>> int(float(3) / 2)
    1