Limiting floats to two decimal points

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

    from decimal import Decimal
    
    
    def round_float(v, ndigits=2, rt_str=False):
        d = Decimal(v)
        v_str = ("{0:.%sf}" % ndigits).format(round(d, ndigits))
        if rt_str:
            return v_str
        return Decimal(v_str)
    

    Results:

    Python 3.6.1 (default, Dec 11 2018, 17:41:10)
    >>> round_float(3.1415926)
    Decimal('3.14')
    >>> round_float(3.1445926)
    Decimal('3.14')
    >>> round_float(3.1455926)
    Decimal('3.15')
    >>> round_float(3.1455926, rt_str=True)
    '3.15'
    >>> str(round_float(3.1455926))
    '3.15'
    

提交回复
热议问题