在 Python 2.7 中四舍五入到两位小数? [英] Rounding to two decimal places in Python 2.7?
本文介绍了在 Python 2.7 中四舍五入到两位小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 Python 2.7 如何将我的数字四舍五入到小数点后两位而不是它给出的 10 位左右?
print "结果 1 的财务回报 =","$"+str(out1)
解决方案
使用内置函数 round()
:
或者内置函数format()
:
或新样式字符串格式:
<预><代码>>>>"{:.2f}".format(1.2345)'1.23>>>"{:.2f}".format(1.679)'1.68'或旧式字符串格式:
<预><代码>>>>"%.2f" % (1.679)'1.68'关于round
的帮助:
Using Python 2.7 how do I round my numbers to two decimal places rather than the 10 or so it gives?
print "financial return of outcome 1 =","$"+str(out1)
解决方案
Use the built-in function round()
:
>>> round(1.2345,2)
1.23
>>> round(1.5145,2)
1.51
>>> round(1.679,2)
1.68
Or built-in function format()
:
>>> format(1.2345, '.2f')
'1.23'
>>> format(1.679, '.2f')
'1.68'
Or new style string formatting:
>>> "{:.2f}".format(1.2345)
'1.23
>>> "{:.2f}".format(1.679)
'1.68'
Or old style string formatting:
>>> "%.2f" % (1.679)
'1.68'
help on round
:
>>> print round.__doc__
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
这篇关于在 Python 2.7 中四舍五入到两位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文