Python - Float number Truncation toward zero regardless of sign

Introduction

To do truncation toward zero regardless of sign, you can always run a float division result through math.trunc, regardless of Python version:

c:\python33\python 
import math 
>>> 5 / -2                      # Keep remainder 
-2.5 
>>> 5 // -2                     # Floor below result 
-3 
>>> math.trunc(5 / -2)          # Truncate instead of floor (same as int()) 
-2 

c:\code> c:\python27\python 
>>> import math 
>>> 5 / float(-2)               # Remainder in 2.X 
-2.5 
>>> 5 / -2, 5 // -2             # Floor in 2.X 
(-3, -3) 
>>> math.trunc(5 / float(-2))   # Truncate in 2.X 
-2 

Related Topic