Limiting floats to two decimal points

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

    The answers I saw didn't work with the float(52.15) case. After some tests, there is the solution that I'm using:

    import decimal
            
    def value_to_decimal(value, decimal_places):
        decimal.getcontext().rounding = decimal.ROUND_HALF_UP  # define rounding method
        return decimal.Decimal(str(float(value))).quantize(decimal.Decimal('1e-{}'.format(decimal_places)))
    

    (The conversion of the 'value' to float and then string is very important, that way, 'value' can be of the type float, decimal, integer or string!)

    Hope this helps anyone.

提交回复
热议问题