Problems with conversion of values in strings to integers
Jørgen Cederberg
jorgencederberg at hotmail.com
Mon Oct 6 08:59:47 EDT 2003
Peter Otten wrote:
> 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.
>>
<snip examples of converting strings with int()>
>>
>> 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)
Thanks a lot for the function. It solves the problem elegantly.
/Jorgen
More information about the Python-list
mailing list