int vs. float

Steve D'Aprano steve+python at pearwood.info
Sat Feb 11 22:38:27 EST 2017


On Sat, 11 Feb 2017 06:00 pm, Amit Yaron wrote:

> Another option:
> Use 'float' instead of 'int'. and check using the method  'is_integer'
> of floating point numbers:
> 
>  >>> 3.5.is_integer()
> False
>  >>> 4.0.is_integer()
> True


A bad option...

py> float('12345678901234567')
1.2345678901234568e+16

Notice the last digit of the mantissa?


Beyond a certain value, *all* floats are integer, because floats don't have
enough precision to include a fractional portion. 

py> float('12345678901234567.12345').is_integer()
True


The safest way to treat this is to attempt to convert to an int, if that
succeeds return the int; if it fails, try to convert to a float, and if
that succeeds, return the float.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list