str to float (rounded)

Diez B. Roggisch deets at nospam.web.de
Tue Jun 10 11:27:22 EDT 2008


> 
> If I do the next :
> 
>  t1 = [(round(float(x),1), round(float(y),2)) for x, y in t]
> 
> I get the long float as :
> 
> [(35.799999999999997, -0.23999999999999999), (33.299999999999997,
> -2.71), (33.600000000000001,-2.4199999999999999)]
> 
> But I would have a float with 2 decimal numbers.

There is no such thing as a float with only two decimal numbers. This has
been discussed on this ML a bazillion times - what you see above are
rounding errors due to the approximation of decimal values by binary
floating points. 

You can *convert a float to a string* and specify a precision when printing:

>>> print "%.2f" % 2.4199999999999999999999999
2.42

Or you can use the module decimal to work with numbers base 10 - which you
can also limit to certain precisions. See a recent thread on this ML,
google for "Alternative to decimal type"


Diez





More information about the Python-list mailing list