Limiting floats to two decimal points

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

    For fixing the floating point in type-dynamic languages such as Python and JavaScript, I use this technique

    # For example:
    a = 70000
    b = 0.14
    c = a * b
    
    print c # Prints 980.0000000002
    # Try to fix
    c = int(c * 10000)/100000
    print c # Prints 980
    

    You can also use Decimal as following:

    from decimal import *
    getcontext().prec = 6
    Decimal(1) / Decimal(7)
    # Results in 6 precision -> Decimal('0.142857')
    
    getcontext().prec = 28
    Decimal(1) / Decimal(7)
    # Results in 28 precision -> Decimal('0.1428571428571428571428571429')
    

提交回复
热议问题