Python 3.x rounding behavior

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

    Just to add here an important note from documentation:

    https://docs.python.org/dev/library/functions.html#round

    Note

    The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

    So don't be surprised to get following results in Python 3.2:

    >>> round(0.25,1), round(0.35,1), round(0.45,1), round(0.55,1)
    (0.2, 0.3, 0.5, 0.6)
    
    >>> round(0.025,2), round(0.035,2), round(0.045,2), round(0.055,2)
    (0.03, 0.04, 0.04, 0.06)
    

提交回复
热议问题