convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'

Kam-Hung Soh kamhung.soh at gmail.com
Wed May 28 20:02:29 EDT 2008


Matthias Bläsing wrote:
> Am Wed, 28 May 2008 10:41:51 -0700 schrieb davidj411:
> 
>> I like the str2num function approach, but then i get left with a float
>> that has more than 2 decimal spaces , i.e. 11.50 becomes
>> 11.449999999999999 and round will not fix that.
> 
> Welcome to the wonderful world of floating point numbers. For your usage 
> you want 10-based numbers. Have a look at the decimal module:
> 
>>>> from  decimal import Decimal
>>>> a = Decimal("11.45")
>>>> a
> Decimal("11.45")
>>>> str(a)
> '11.45'
>>>> a + 1
> Decimal("12.45")
>>>> a + Decimal("1.55")
> Decimal("13.00")
> 
> HTH
> 
> Matthias
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Thanks for the tip, Matthias.  I knew that there had to be a way to 
handle arbitrary precision numbers.

-- 
Kam-Hung Soh <a href="http://kamhungsoh.com/blog">Software Salariman</a>




More information about the Python-list mailing list