How to round away from 0 in Python 3.x?

  • A+

In Python 2 rounding is done away from 0, so, for example, round(0.5) is 1.0.
In Python 3.x, however, rounding is done toward the even choice, so round(0.5) is 0.
What function can I use in Python 3.x to get the old behavior?


If your code is not particularly performance sensitive, you can use the standard decimal library to achieve the result you want. Decimal().quantize() allows choosing the rounding method:

from decimal import Decimal, ROUND_HALF_UP result = float(Decimal(0.5).quantize(Decimal(0), rounding=ROUND_HALF_UP)) print(result)  # Will output 1.0 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: