Convert '165.0' to int

Grant Edwards invalid at invalid.invalid
Fri Jul 22 16:21:31 CEST 2011


On 2011-07-22, Billy Mays <noway at nohow.com> wrote:
> On 7/21/2011 10:40 PM, Thomas 'PointedEars' Lahn wrote:
>> Billy Mays wrote:
>>
>>> On 07/21/2011 08:46 AM, Web Dreamer wrote:
>>>> If you do not want to use 'float()' try:
>>>>
>>>> int(x.split('.')[0])
>>>
>>> This is right.
>>
>> Assuming that the value of `x' is in the proper format, of course.  Else you
>> might easily cut to the first one to three digits of a string representation
>> (if `.' is the thousands separator of the locale, e. g.)
>
> The point (which was clear to me) was to convert a properly formatted
> string representation of a floating point number to an integer.

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.

> We might also assume the number could be a hex encoded float or be in
> scientific notation.  If the input is not properly formatted, it is 
> unreasonable for us to return a correct value.

What does "properly formatted" mean?  Who says that the character
representing the radix is "." rather than ","?

>>> 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.

-- 
Grant Edwards               grant.b.edwards        Yow! Maybe we could paint
                                  at               GOLDIE HAWN a rich PRUSSIAN
                              gmail.com            BLUE --



More information about the Python-list mailing list