Python 3.x rounding behavior

前端 未结 11 1683
别那么骄傲
别那么骄傲 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 00:49

    Some cases:

    in: Decimal(75.29 / 2).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
    in: round(75.29 / 2, 2)
    out: 37.65 GOOD
    
    in: Decimal(85.55 / 2).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
    in: round(85.55 / 2, 2)
    out: 42.77 BAD
    

    For fix:

    in: round(75.29 / 2 + 0.00001, 2)
    out: 37.65 GOOD
    in: round(85.55 / 2 + 0.00001, 2)
    out: 42.78 GOOD
    

    If you want more decimals, for example 4, you should add (+ 0.0000001).

    Work for me.

提交回复
热议问题