vlangen
vlangen

Reputation: 520

What is the simplest way to round floats correctly in Python?

As many of you know already, sometimes Python rounds for instance 3.75.... to 3.7 rather than 3.8, which is of course a problem. (I'm on Python 3.)

Another user presented as a solution here a very nice function in Python that he called round_exact (you can find this in Stack Overflow by searching), but unfortunately even this function is suboptimal for my purposes, as it seems to consider a zero in the last decimal place always redundant and cuts it away.

(I mean, i would like to see 1.695 to be 1.70, if I wanted two decimals, rather than 1.7.)

So, I would still like to ask for additional opinions on how to deal with Python's shortcomings in rounding floats.

Upvotes: 1

Views: 666

Answers (2)

Raymond Hettinger
Raymond Hettinger

Reputation: 226171

The decimal module allows precise control over rounding and it can retain trailing zeros:

>>> Decimal('1.695').quantize(Decimal('.01'), rounding=ROUND_HALF_UP)
Decimal('1.70')

Upvotes: 3

Makoto
Makoto

Reputation: 106389

For a numerical display, you should look to print two decimals instead of one. That can be accomplished with a specialized formatted print statement.

"{:.2f}".format(7.1) # prints 7.10

If you're concerned about there being decimal imprecision, look into the decimal module. It provides up to 28 digits of accuracy and can be used to reliably print out those numbers as well.

Upvotes: 1

Related Questions