Convert '165.0' to int

Billy Mays 81282ed9a88799d21e77957df2d84bd6514d9af6 at
Fri Jul 22 16:49:26 CEST 2011

On 07/22/2011 10:21 AM, Grant Edwards wrote:
> While that may be clear to you, that's because you've made some
> assumptions.  "Convert a properly formatted string representation of a
> floating point number to an integer" is not a rigorous definition.
> What does "properly formatted" mean?  Who says that the character
> representing the radix is "." rather than ","?

Properly formatted means that Python would accept the string as an 
argument to float() without raising an exception.

>>>> Notice the last digit switched from a 3 to a 2?  Floats in python don't
>>>> have arbitrary accuracy.  You would need to import decimal and use it
>>>> for rounding to work properly.
>>> It should be floor() though, for that is what int() does.
>> Um, what?
> The example given by the OP implied that int(float(s)) did what he
> wanted.  That is _not_ rounding the float.  It's the equivalent of
> using the floor() function.

int(float(s)) does the "right thing" for short strings.  However, for 
longer strings it loses information due to the way floats are 
implemented in Python.  Python uses the IEEE754 double precision 
datatype(double) to implement floating point numbers.  The floats only 
have 53 bits in the mantissa portion of the number which means python 
can only accurately represent integers up to 2**53 correctly as floats.

Compare this to integers in Python, which are automatically upcast to 
longs if overflow would occur.  The int() call will never lose accuracy 
when converting a properly formatted integer string.  float() will lose 
accuracy, even if the float string is properly formatted.  The is no 
floor() being called or used, this is simply the behavior of the float 

You seem to be worrying about python producing invalid output for 
invalid input (period  separated numbers).  You should be worrying if 
valid input (a very long float string) produces invalid output.


More information about the Python-list mailing list