开发者

Precision in python

开发者 https://www.devze.com 2023-02-15 16:35 出处:网络
How can write a print statement in python that will p开发者_Go百科rint exactly 2 digits after decimal?print \"{0:.2f}\".format(your_number)

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))
0

精彩评论

暂无评论...
验证码 换一张
取 消