int('2.1') does not work while int(float('2.1')) does

Vineet Jain vineet at eswap.com
Tue Apr 6 00:15:58 EDT 2004


I understand the reason that it is done. I don't agree with though. Given
the following use case: (which is how I discovered the problem).

read a csv file which has

int1, int2, int3, etc...

In one of the files that was passed to me the ints were replaced with int.00
and the program failed. So now I have to do int(float(csvfield)) which does
not make sense to me.

the answers to your question:

>>Should it truncate, round to negative infinity round to positive infinity,
round
>>to zero, what?

is that it should behave exatly as when it encounters a float number. From
my mind there is no difference between

int('2.1')
int(float('2.1'))

If the second is allowed (which has to be), then the first should also be
allowed.

VJ

-----Original Message-----
From: python-list-bounces+vineet=eswap.com at python.org
[mailto:python-list-bounces+vineet=eswap.com at python.org]On Behalf Of
Erik Max Francis
Sent: Monday, April 05, 2004 10:35 PM
To: python-list at python.org
Subject: Re: int('2.1') does not work while int(float('2.1')) does


Vineet Jain wrote:

> int('2.1') does not work while int(float('2.1')) does. If int can
> covert a
> float object then there is no reason why a float string should not be
> converted too.
>
> When I do int('2.1') I get the following error:
>
> >>> a = int('2.0')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): 2.0
>
> This does not seem very pythonic

There's a fundamental difference between an int and a float.  If the
string you're trying to convert looks like a float, that means it
doesn't look like an int.

With your first example of '2.1', what should it mean?  Should it
truncate, round to negative infinity round to positive infinity, round
to zero, what?  Python can't guess for you, so it shouldn't try.  Thus
it's an error.

--
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ If I had another face, do you think I'd wear this one?
    -- Abraham Lincoln
--
http://mail.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list