Limiting floats to two decimal points

前端 未结 28 3206
你的背包
你的背包 2020-11-21 04:57

I want a to be rounded to 13.95.

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999

The ro

28条回答
  •  一向
    一向 (楼主)
    2020-11-21 05:19

    The Python tutorial has an appendix called Floating Point Arithmetic: Issues and Limitations. Read it. It explains what is happening and why Python is doing its best. It has even an example that matches yours. Let me quote a bit:

    >>> 0.1
    0.10000000000000001
    

    you may be tempted to use the round() function to chop it back to the single digit you expect. But that makes no difference:

    >>> round(0.1, 1)
    0.10000000000000001
    

    The problem is that the binary floating-point value stored for “0.1” was already the best possible binary approximation to 1/10, so trying to round it again can’t make it better: it was already as good as it gets.

    Another consequence is that since 0.1 is not exactly 1/10, summing ten values of 0.1 may not yield exactly 1.0, either:

    >>> sum = 0.0
    >>> for i in range(10):
    ...     sum += 0.1
    ...
    >>> sum
    0.99999999999999989
    

    One alternative and solution to your problems would be using the decimal module.

提交回复
热议问题