Search code examples
pythonpython-2.7

How to round 0.055 to 0.06 in Python?


Result of a simple division -34.11/2 returns -17.055 Is there a python function that would return round up decimal? I am expecting to see -17.06

And yes I checked these answers, but neither can answer this question: Round up to Second Decimal Place in Python

How to round to nearest decimal in Python

Increment a Python floating point value by the smallest possible amount Python round to nearest 0.25

Any help would be greatly appreciated. Thanks!


Solution

  • This is a floating point limitation; get around it by using decimal.Decimal.

    >>> from decimal import Decimal
    >>> Decimal(-34.11/2)  # See? Not quite the value you thought.
    Decimal('-17.05499999999999971578290569595992565155029296875')
    >>> Decimal(-34.11) / Decimal(2)  # This doesn't quite work either, because -34.11 is already a little bit off.
    Decimal('-17.05499999999999971578290570')
    >>> Decimal("-34.11") / Decimal("2")
    Decimal('-17.055')
    >>> round(Decimal("-34.11") / Decimal("2"), 2)
    Decimal('-17.06')