【问题标题】:python decimal rounding issuepython小数舍入问题
【发布时间】:2021-10-12 22:30:12
【问题描述】:
>>> round((611.05/10.0),2)
61.1
>>> round((611.05/10.0),3)
61.105

我怎样才能获得 61.11?

我尝试了以下但结果相同

>>> ctx = decimal.getcontext()
>>> ctx.rounding = decimal.ROUND_HALF_UP

【问题讨论】:

标签: python python-3.x python-2.7


【解决方案1】:

decimal 上下文应用于十进制计算:

from decimal import Decimal, ROUND_HALF_UP

non_rounded = Decimal("611.05")/Decimal("10.0")
non_rounded.quantize(Decimal(".01"), rounding=ROUND_HALF_UP)

返回

Decimal('61.11')

编辑:使用quantize 而不是round reference

【讨论】:

  • 这在 python3.x 中运行良好。但不是在 2.x 中。它给出了相同的结果。
  • 小数有自己的舍入方法,我已经用我的 py27 和 py36 上的工作版本更新了 sn-p
猜你喜欢
  • 2020-09-17
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
相关资源
最近更新 更多