python 小数四舍五入问题
python decimal rounding issue
>>> 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
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)
Returns
Decimal('61.11')
编辑:使用 quantize
而不是 round
reference
>>> 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
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)
Returns
Decimal('61.11')
编辑:使用 quantize
而不是 round
reference