0
>>> round((611.05/10.0),2)
61.1
>>> round((611.05/10.0),3)
61.105

How can I get 61.11 ?

I tried with following but results are same

>>> ctx = decimal.getcontext()
>>> ctx.rounding = decimal.ROUND_HALF_UP
Bhavesh Odedra
  • 10,990
  • 12
  • 33
  • 58
  • 2
    Try `format(611.05 / 10.0, ".40f")` - it's `61.10499999999...`, slightly _less_ than the half you're trying to round up. – jonrsharpe Oct 12 '21 at 22:34
  • 1
    You can't get 61.11, because 61.1049 should never round to 61.11. Check this https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Grismar Oct 12 '21 at 22:36
  • Welcome to the world of floating point math https://0.30000000000000004.com/ – Samathingamajig Oct 12 '21 at 22:37

1 Answers1

1

The decimal context is applied to decimal calculations:

from decimal import Decimal, ROUND_HALF_UP

non_rounded = Decimal("611.05")/Decimal("10.0")
non_rounded.quantize(Decimal(".01"), rounding=ROUND_HALF_UP)

Returns

Decimal('61.11')

EDIT: using quantize instead of round reference

luigibertaco
  • 1,112
  • 5
  • 21