Round float to 2 digits after dot in python

Viewed 33071

I'm using this code:

f = 0.3223322
float('%.2f' % (f))

Is there more pythonic, less verbose method without 2 castings? Using round is discouraging by the following note from the documentation

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

5 Answers

You can use Decimal with quantize and rounding. ROUND_HALF_UP is a mathematical rounding.

from decimal import Decimal, ROUND_HALF_UP

>>> Decimal('123.527').quantize(Decimal('.01'), rounding=ROUND_HALF_UP)
Decimal('123.53')

>>> Decimal('123.525').quantize(Decimal('.01'), rounding=ROUND_HALF_UP)
Decimal('123.53')
Related