Search code examples
pythonmathfloating-pointrounding

how python ROUND_HALF_EVEN works


Why am i getting 0.27 as my answer for round(0.265, 2) even after my global context "rounding" is set to ROUND_HALF_EVEN?

Here is my code.

import decimal
from decimal import Decimal

print(decimal.getcontext())

a = 0.265
print(Decimal(a))
print(round(a, 2)) # current output: 0.27

Here is the output

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
0.26500000000000001332267629550187848508358001708984375
0.27

I'm confused as i think output should be 0.26 instead on 0.27 since rounding is set to ROUND_HALF_EVEN.


Solution

  • 0.26500000000000001332267629550187848508358001708984375 is a binary approximation of 0.265 and is closer to 0.27.

    Try a = Decimal('0.265') to maintain precision.

    From https://www.programiz.com/python-programming/methods/built-in/round