有人能解释或提出为什么当我在Python 3轮的十进制设置为圆形半升的背景下修复后,便将2.5〜2,而在Python二轮正确地3:Python 3的小数四舍五入半下来ROUND_HALF_UP方面
的Python 3.4.3和3.5.2:
>>> import decimal
>>> context = decimal.getcontext()
>>> context.rounding = decimal.ROUND_HALF_UP
>>> round(decimal.Decimal('2.5'))
2
>>> decimal.Decimal('2.5').__round__()
2
>>> decimal.Decimal('2.5').quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP)
Decimal('3')
的Python 2.7.6:
>>> import decimal
>>> context = decimal.getcontext()
>>> context.rounding = decimal.ROUND_HALF_UP
>>> round(decimal.Decimal('2.5'))
3.0
>>> decimal.Decimal('2.5').quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP)
Decimal('3')
感谢@Duncan的解释,尝试理解这些东西总是很好。根据是否指定ndigits,返回不同的_type_似乎很奇怪。 –
作为一个插件,python 3文档声明它委托给'number .__ round __(ndigits)',而'decimal'模块实现了它自己的'__round__'方法 –
@Dunca,它看起来是一个int,而不是float though:“如果ndigits被省略或者是None,它将返回最接近它的输入的整数。” https://docs.python.org/3/library/functions.html#round –