Precision in python
How can write a print statement in python that will p开发者_Go百科rint exactly 2 digits after decimal?
print "{0:.2f}".format(your_number)
This is explained in detail in the Python Documentation.
x = 4.12121212
print '%.2f' % x
Basically, the same way you'd do it in C with printf.
f = 4.55556
print "{0:.2f}".format(f)
There is also a special module for fixed point decimals. More: http://docs.python.org/library/decimal.html
this is django float format template tag, that may be interest for you to reading ...
at line 92 :
django float format template tag
Another efficient way of doing this is:
import sys
a = 0.5
sys.stdout.write(str('%0.2f'%a))
精彩评论