Safest way to convert float to integer in python? Safest way to convert float to integer in python? python python

# Safest way to convert float to integer in python?

All integers that can be represented by floating point numbers have an exact representation. So you can safely use `int` on the result. Inexact representations occur only if you are trying to represent a rational number with a denominator that is not a power of two.

That this works is not trivial at all! It's a property of the IEEE floating point representation that int∘floor = ⌊⋅⌋ if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.

To quote from Wikipedia,

Any integer with absolute value less than or equal to 224 can be exactly represented in the single precision format, and any integer with absolute value less than or equal to 253 can be exactly represented in the double precision format.

Use `int(your non integer number)` will nail it.

``print int(2.3) # "2"print int(math.sqrt(5)) # "2"``

You could use the round function. If you use no second parameter (# of significant digits) then I think you will get the behavior you want.

IDLE output.

``>>> round(2.99999999999)3>>> round(2.6)3>>> round(2.5)3>>> round(2.4)2`` 