简体   繁体   中英

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.

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')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM