简体   繁体   中英

Precision in python

如何在python中编写一个打印语句,它将在十进制后正好打印2位数?

print "{0:.2f}".format(your_number)

这在Python文档中有详细解释。

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

Another efficient way of doing this is:

import sys
a = 0.5
sys.stdout.write(str('%0.2f'%a))

this is django float format template tag, that may be interest for you to reading ...

at line 92 :

django float format template tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM