Limiting floats to two decimal points

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

    Use combination of Decimal object and round() method.

    Python 3.7.3
    >>> from decimal import Decimal
    >>> d1 = Decimal (13.949999999999999) # define a Decimal
    >>> d1 
    Decimal('13.949999999999999289457264239899814128875732421875')
    >>> d2 = round(d1, 2) # round to 2 decimals
    >>> d2
    Decimal('13.95')
    

提交回复
热议问题