1/2
gives
0
as it should. However,
-1/2
gives
-1
Try this. Only works for numbers greater than -1
import math
x = .5
y = -.5
print math.floor(math.fabs(x))
>> 0
print math.floor(math.fabs(y))
>> 0
Correct code to do this is, in my opinion, too obscure to write as a 1-liner. So I'd put it in a function, like:
def int0div(a, b):
q = a // b
if q < 0 and b*q != a:
q += 1
return q
Good features: it works for any size of int, doesn't make any adjustment to the raw (a//b
) result unless necessary, only does one division (%
also does a division under the covers), and doesn't create any integers larger than the inputs. Those may or may not matter in your application; they become more important (for speed) if you use "big" integers.