[Tutor] floats

Emile van Sebille emile at fenx.com
Fri Dec 3 20:01:19 CET 2010


On 12/3/2010 10:52 AM Christopher Spears said...
>
> 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?

If you want control over the precision I'd use the decimal module.

 >>> x
1.1666666699999999
 >>> y = decimal.Decimal("%.2f" % x)
 >>> y
Decimal('1.17')
 >>>


Emile



More information about the Tutor mailing list