Problems with conversion of values in strings to integers

Peter Otten __peter__ at web.de
Mon Oct 6 08:06:26 EDT 2003


Jørgen Cederberg wrote:

> Hi,
> 
> using Python 2.2.1 on Windows and QNX I'm having trouble understandig
> why int() raises a ValueError exception upon converting strings.
> 
>  >>> int('-10')
> -10
>  >>> int('10')
> 10
>  >>> int(10.1)
> 10
>  >>> int('10.1')
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): 10.1
> 
> This is quite frustating. The only solution I can see is to do:
>  >>> int(float('10.1'))
> 10
> 
> Is this the only solution or are there any other way to do this?


There is more than one way to convert a string representing a fp number to
an integer:

>>> int(float("1.999"))
1

>>> int(round(float("1.999")))
2

I think it's good that Python does not make the decision for you. Once you
have decided which route to go you can easily wrap it into a helper
function, e. g.

def toInt(s):
    try:
        return int(s)
    except ValueError:
        return int(round(float(s)))

(When dealing with user input, things are a little more complicated, as the
decimal separator changes between locales)

Peter





More information about the Python-list mailing list