Limiting floats to two decimal points

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

    It's simple like 1,2,3:

    1. use decimal module for fast correctly-rounded decimal floating point arithmetic:

      d=Decimal(10000000.0000009)

    to achieve rounding:

       d.quantize(Decimal('0.01'))
    

    will results with Decimal('10000000.00')

    1. make above DRY:
        def round_decimal(number, exponent='0.01'):
            decimal_value = Decimal(number)
            return decimal_value.quantize(Decimal(exponent))
    

    OR

        def round_decimal(number, decimal_places=2):
            decimal_value = Decimal(number)
            return decimal_value.quantize(Decimal(10) ** -decimal_places)
    
    1. upvote this answer :)

    PS: critique of others: formatting is not rounding.

提交回复
热议问题