Convert '165.0' to int
Thomas 'PointedEars' Lahn
PointedEars at web.de
Thu Jul 21 22:40:35 EDT 2011
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.)
>> But, the problem is the same as with int(float(x)), the integer number is
>> still not as close as possible as the original float value.
>>
>> I would in fact consider doing this:
>>
>> int(round(float(x)))
>
> This is wrong, since there is a loss of information in the float cast:
>
> >>> float('9007199254740993.0')
> 9007199254740992.0
>
> 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.
--
PointedEars
Bitte keine Kopien per E-Mail. / Please do not Cc: me.
More information about the Python-list
mailing list