Limiting floats to two decimal points

前端 未结 28 3140
你的背包
你的背包 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:28

    There are new format specifications, String Format Specification Mini-Language:

    You can do the same as:

    "{:.2f}".format(13.949999999999999)
    

    Note 1: the above returns a string. In order to get as float, simply wrap with float(...):

    float("{:.2f}".format(13.949999999999999))
    

    Note 2: wrapping with float() doesn't change anything:

    >>> x = 13.949999999999999999
    >>> x
    13.95
    >>> g = float("{:.2f}".format(x))
    >>> g
    13.95
    >>> x == g
    True
    >>> h = round(x, 2)
    >>> h
    13.95
    >>> x == h
    True
    

提交回复
热议问题