The round context isn't used here because you've passed in a float initially. That float doesn't represent exactly what you want and is already higher than the target. If you want to be exact, you have to pass in a string and let Decimal do the conversion.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
>>> Decimal(. 505 ) #.505 isn't exact Decimal( '0.50500000000000000444089209850062616169452667236328125' ) #Not "5.05". Is closer to 5.1 >>> round (Decimal(. 505 ), 2 ) Decimal( '0.51' ) # Instead of float, pass in a string. '.505' is exact. >>> Decimal( '.505' ) Decimal( '0.505' ) >>> round (Decimal( '.505' ), 2 ) # now the context matters Decimal( '0.50' ) >>> decimal.getcontext().rounding = decimal.ROUND_HALF_UP >>> round (Decimal( '.505' ), 2 ) Decimal( '0.51' ) |