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
3
  • 2
    Try format(611.05 / 10.0, ".40f") - it's 61.10499999999..., slightly less than the half you're trying to round up. Commented Oct 12, 2021 at 22:34
  • 1
    You can't get 61.11, because 61.1049 should never round to 61.11. Check this stackoverflow.com/questions/588004/… Commented Oct 12, 2021 at 22:36
  • Welcome to the world of floating point math 0.30000000000000004.com Commented Oct 12, 2021 at 22:37

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is working great in python3.x. But not in 2.x. It gives same.
Decimals have their own rounding methods, I've updated the snippet with a working version on my py27 and py36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.