string to float, putting in list/tuple

Bjarke Dahl Ebert bebert at worldonline.dk
Mon Oct 14 16:09:19 EDT 2002


"Daniel Barié" <daniel0603 at me-barie.de> wrote in message
news:3DAB179F.6070200 at me-barie.de...

> Now I want to convert these to float, using the builtin float()
> function. The results are quite as expected: float(Sl) = 0.03169,
> float(SS31) = -3.01, float(SS41) = -3.01.
>
> But when stuffing a list with these floats the result is not as I
> expect it to be:
> [0.031690000000000003, -3.0099999999999998, -3.0099999999999998]

This must be a FAQ.

It is not true that float(SS41)=-3.01, it just looks that way ;-)

>>> a = 3.1
>>> a
3.1000000000000001
>>> print a
3.1
>>> str(a), repr(a)
('3.1', '3.1000000000000001')

You are seeing the rounding errors coming from the fact that 31/10 cannot be
expressed precisely with binary numbers.
The reason why you see a difference between 'a' and '[a]', is that the
string representation of '[a]' is the same as repr([a]), which uses 'repr'
on all the list entries.
'repr' on a number uses maximum precision. 'str' on a number does some
rounding to avoid all these decimals.


Bjarke







More information about the Python-list mailing list