Can someone help me with some simple math logic?


why does x % 1 return the same value as abs(x) - abs(int(x)) ?
I don't understand how x % 1 is evaluated...

I came up with the abs(x) - abs(int(x)) method while doing the is_int() exercise in the Python practice makes perfect lesson, but found that someone used the x%1 method which looks a lot cleaner to me and I'd like to understand how it works.


The expression x % 1 yields the decimal fraction portion of a float.

print 10.5 % 1             # 0.5

It doesn't make a reliable test for integers, in and of itself, since it does not convert the float to an integer.

x = 10.5
print x - (x % 1)          # 10.0

It's not a giant leap to get the integer out of this, though.

print int(x - (x % 1))     # 10