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

blacktrance picture blacktrance · Nov 12, 2013 · Viewed 29.6k times · Source
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?

Answer

Tim picture Tim · Nov 12, 2013

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