Odd ValueError using float

emile emile at fenx.com
Tue Mar 17 16:48:35 EDT 2015


On 03/15/2015 07:01 AM, Peter Otten wrote:
> Probably not helpful, but I can provoke the behaviour you see by toggling
> bytes with ctypes, thus simulating a corrupted str object:
>
> Python 2.7.6 (default, Mar 22 2014, 22:59:56)
> [GCC 4.8.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import ctypes
>>>> s = "41.700000000000003"
>>>> ctypes.c_ubyte.from_address(id(s) + 16).value = 1
>>>> s
> '4'
>>>> len(s)
> 1
>>>> float(s)
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> ValueError: invalid literal for float(): 41.700000000000003
>>>> int(s)
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> ValueError: invalid literal for int() with base 10: '41.700000000000003'


I dug through the code and ctypes was in the mix.  Without discovering 
the actual issue, I did manage to work around the issue by replacing:

  val = round(float(decval),1)

with

  val = round(float("".join([ii if ii=="." else str(int(ii)) for ii in 
decval])),1)


Thanks.







More information about the Python-list mailing list