Convert '165.0' to int
invalid at invalid.invalid
Fri Jul 22 10:58:09 EDT 2011
On 2011-07-22, Billy Mays <81282ed9a88799d21e77957df2d84bd6514d9af6 at myhashismyemail.com> wrote:
> 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.
Then you can't assume that '.' is the radix character.
>>>>> 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.
True but irrelevent to the point that using a rounding conversion is
_not_ equivelent to the OP's example using int(float()).
> 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 datatype.
> 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.
No, I'm talking about the claim that you should use decmial so that
you can use rounding when the OP's example showed that rounding was
not what he wanted.
Grant Edwards grant.b.edwards Yow! Boys, you have ALL
at been selected to LEAVE th'
gmail.com PLANET in 15 minutes!!
More information about the Python-list