Ian Witham wrote:
> As Michael points out, you need to explicitly use the round function, as 
> the float formatting merely truncates anything after the second decimal 
> place.

No. I don't know what algorithm it uses for rounding, but it does round:
In [3]: '%.2f' % 6.6666
Out[3]: '6.67'
In [4]: '%.2f' % 6.665
Out[4]: '6.67'
In [5]: '%.2f' % 6.664
Out[5]: '6.66'

The round() function seems to be aware of limits of representation and 
takes them into account. 10.825 is not exactly represented in floating 
point:
In [8]: 10.825
Out[8]: 10.824999999999999

String formatting is literal in its rounding; 10.824999999999999 is 
closer to 10.82 than 10.83:

In [15]: '%.2f' % 10.825
Out[15]: '10.82'

round() seems to know about this:
In [12]: round(10.825, 2)
Out[12]: 10.83

This is not surprising after what is above, but perhaps a bit disturbing:
In [13]: round(10.824999999999999, 2)
Out[13]: 10.83

Kent
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to