Problems with conversion of values in strings to integers
jorgencederberg at hotmail.com
Mon Oct 6 14:59:47 CEST 2003
Peter Otten wrote:
> Jørgen Cederberg wrote:
>> 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'))
>> 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:
> 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):
> 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.
More information about the Python-list