Search code examples
pythonrounding

Fix float precision with decimal numbers


a = 1

for x in range(5):
    a += 0.1
    print(a)

This is the result:

1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004

How can I fix this? Is the round() function the only way? Can I set the precision of a variable before setting its value?


Solution

  • can i set the precision of a variable before setting the value?

    Use the decimal module which, unlike float(), offers arbitrary precision and can represent decimal numbers exactly:

    >>> from decimal import Decimal, getcontext
    >>> 
    >>> getcontext().prec = 5
    >>> 
    >>> a = Decimal('1')
    >>> 
    >>> for x in range(5):
    ...     a += Decimal('0.1')  # note the use of `str` here
    ...     print(a)
    ... 
    1.1000
    1.2000
    1.3000
    1.4000
    1.5000