[Tutor] floats

Joel Goldstick joel.goldstick at gmail.com
Fri Dec 3 20:18:56 CET 2010


On Fri, Dec 3, 2010 at 1:52 PM, Christopher Spears <cspears2002 at yahoo.com>wrote:

>
> I have a float variable that is very long.
>
> >>> float_a = 1.16667
>
> However, I want to pass the value of float_a to float_b, but I want the
> float to be accurate to two decimal points.
>
> >>> float_a = 1.16667
> >>> print "%.2f" % float_a
> 1.17
>
> I tried the following:
>
> >>> float_b = "%.2f" % float_a
> >>> float_b
> '1.17'
> >>> type(float_b)
> <type 'str'>
>
> This doesn't work because it yields a string.
>
> Any suggestions?
>

This would be good to read:
http://docs.python.org/tutorial/floatingpoint.html

If you have:

float_a = 1.66667

and do round(float_a, 2)

you get:
round(1.16667, 2)
1.1699999999999999

I don't think that is what you want, but since floating point arithmetic is
done in binary there are rounding errors.

You might want to look at the decimal module

> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101203/195e1dc3/attachment-0001.html>


More information about the Tutor mailing list