[Tutor] floats

Alan Gauld alan.gauld at btinternet.com
Fri Dec 3 20:15:29 CET 2010


"Christopher Spears" <cspears2002 at yahoo.com> wrote

> I have a float variable that is very long.
>
>>>> float_a = 1.16667

Thats not really very long!

> 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

Rounding issues will give you all sorts of issues here.
However if you really want to round it up or down to 2 digits
then the round() function is what you want.

But I'd be interested in why you need to lose precision
like that, it's not that common a requirement. Usually controlling
the presentation is sufficient (and preferred).

>>>> float_b = "%.2f" % float_a
>>>> float_b
> '1.17'
>>>> type(float_b)
> <type 'str'>
>
> This doesn't work because it yields a string.

It works in that it returns a string representation of what you want.
It doesn't produce a float because *string formatting* can only
produce strings.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list