Python 3.x rounding behavior

前端 未结 11 1932
别那么骄傲
别那么骄傲 2020-11-22 00:41

I was just re-reading What’s New In Python 3.0 and it states:

The round() function rounding strategy and return type have changed. Exact halfway cas

11条回答
  •  天命终不由人
    2020-11-22 01:02

    You can control the rounding you get in Py3000 using the Decimal module:

    >>> decimal.Decimal('3.5').quantize(decimal.Decimal('1'), 
        rounding=decimal.ROUND_HALF_UP)
    >>> Decimal('4')
    
    >>> decimal.Decimal('2.5').quantize(decimal.Decimal('1'),    
        rounding=decimal.ROUND_HALF_EVEN)
    >>> Decimal('2')
    
    >>> decimal.Decimal('3.5').quantize(decimal.Decimal('1'), 
        rounding=decimal.ROUND_HALF_DOWN)
    >>> Decimal('3')
    

提交回复
热议问题