在 Python 2.7 中四舍五入到两位小数? [英] Rounding to two decimal places in Python 2.7?

查看:167
本文介绍了在 Python 2.7 中四舍五入到两位小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Python 2.7 如何将我的数字四舍五入到小数点后两位而不是它给出的 10 位左右?

print "结果 1 的财务回报 =","$"+str(out1)

解决方案

使用内置函数 round():

<预><代码>>>>轮(1.2345,2)1.23>>>回合(1.5145,2)1.51>>>回合(1.679,2)1.68

或者内置函数format():

<预><代码>>>>格式(1.2345,'.2f')'1.23'>>>格式(1.679,'.2f')'1.68'

或新样式字符串格式:

<预><代码>>>>"{:.2f}".format(1.2345)'1.23>>>"{:.2f}".format(1.679)'1.68'

或旧式字符串格式:

<预><代码>>>>"%.2f" % (1.679)'1.68'

关于round的帮助:

<预><代码>>>>打印圆形.__doc__round(number[, ndigits]) ->浮点数将数字舍入到给定精度的十进制数字(默认为 0 位).这总是返回一个浮点数.精度可能为负.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆