Python 3.x rounding behavior

前端 未结 11 1689
别那么骄傲
别那么骄傲 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:01

    Python 3.x rounds .5 values to a neighbour which is even

    assert round(0.5) == 0
    assert round(1.5) == 2
    assert round(2.5) == 2
    
    import decimal
    
    assert decimal.Decimal('0.5').to_integral_value() == 0
    assert decimal.Decimal('1.5').to_integral_value() == 2
    assert decimal.Decimal('2.5').to_integral_value() == 2
    

    however, one can change decimal rounding "back" to always round .5 up, if needed :

    decimal.getcontext().rounding = decimal.ROUND_HALF_UP
    
    assert decimal.Decimal('0.5').to_integral_value() == 1
    assert decimal.Decimal('1.5').to_integral_value() == 2
    assert decimal.Decimal('2.5').to_integral_value() == 3
    
    i = int(decimal.Decimal('2.5').to_integral_value()) # to get an int
    assert i == 3
    assert type(i) is int
    

提交回复
热议问题