在Python 2.7中舍入到小数点后两位?

RCN*_*RCN 81 python rounding python-2.7

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

print "financial return of outcome 1 =","$"+str(out1)
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 192

使用内置功能round():

>>> round(1.2345,2)
1.23
>>> round(1.5145,2)
1.51
>>> round(1.679,2)
1.68
Run Code Online (Sandbox Code Playgroud)

或内置功能format():

>>> format(1.2345, '.2f')
'1.23'
>>> format(1.679, '.2f')
'1.68'
Run Code Online (Sandbox Code Playgroud)

或者新样式字符串格式:

>>> "{:.2f}".format(1.2345)
'1.23
>>> "{:.2f}".format(1.679)
'1.68'
Run Code Online (Sandbox Code Playgroud)

或旧式字符串格式:

>>> "%.2f" % (1.679)
'1.68'
Run Code Online (Sandbox Code Playgroud)

帮助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.
Run Code Online (Sandbox Code Playgroud)

  • 凉!我不知道内置的那种格式.在探索了更多之后,我认为如果浮点误差绝对不可接受,这是最精确的舍入方式:`十进制('123.345').量化(十进制('1.00'),舍入=十进制.ROUND_HALF_UP)`给你`十进制( '123.35')`.另一方面`十进制(格式(十进制('123.345'),'.2f'))`给你`十进制('123.34')`因为123.345的二进制表示小于123.345. (9认同)
  • 使用Decimal时,字符串格式化方法很有用.例如`十进制("{:.2f}".格式(val))` (2认同)

Ron*_*xão 46

既然你在谈论金融数据,你不希望使用浮点运算.你最好使用Decimal.

>>> from decimal import Decimal
>>> Decimal("33.505")
Decimal('33.505')
Run Code Online (Sandbox Code Playgroud)

使用新样式的文本输出格式format()(默认为半舍入舍入):

>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.505")))
financial return of outcome 1 = 33.50
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.515")))
financial return of outcome 1 = 33.52
Run Code Online (Sandbox Code Playgroud)

查看由于浮点不精确导致的舍入差异:

>>> round(33.505, 2)
33.51
>>> round(Decimal("33.505"), 2)  # This converts back to float (wrong)
33.51
>>> Decimal(33.505)  # Don't init Decimal from floating-point
Decimal('33.50500000000000255795384873636066913604736328125')
Run Code Online (Sandbox Code Playgroud)

适当的方法来舍入财务价值:

>>> Decimal("33.505").quantize(Decimal("0.01"))  # Half-even rounding by default
Decimal('33.50')
Run Code Online (Sandbox Code Playgroud)

在不同的交易中进行其他类型的舍入也很常见:

>>> import decimal
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_DOWN)
Decimal('33.50')
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_UP)
Decimal('33.51')
Run Code Online (Sandbox Code Playgroud)

请记住,如果您正在模拟退货结果,您可能必须在每个利息期进行回合,因为您无法支付/接收分数,也不会获得超过分数的利息.对于模拟,由于固有的不确定性而使用浮点是很常见的,但如果这样做,请始终记住错误存在.因此,即使是固定利息投资也可能因此而有所不同.


Ter*_*ryA 5

您也可以使用str.format():

>>> print "financial return of outcome 1 = {:.2f}".format(1.23456)
financial return of outcome 1 = 1.23
Run Code Online (Sandbox Code Playgroud)