The most direct way to take the ceiling of a decimal instance of x is to use x.to_integral_exact(rounding=ROUND_CEILING) . There is no need to bother with context. Note that this sets the Inexact and Rounded flags, where necessary; if you don't need flags, use x.to_integral_value(rounding=ROUND_CEILING) instead. Example:
>>> from decimal import Decimal, ROUND_CEILING >>> x = Decimal('-123.456') >>> x.to_integral_exact(rounding=ROUND_CEILING) Decimal('-123')
Unlike most Decimal methods, the to_integral_exact and to_integral_value are independent of the accuracy of the current context, so you donโt have to worry about changing the accuracy:
>>> from decimal import getcontext >>> getcontext().prec = 2 >>> x.to_integral_exact(rounding=ROUND_CEILING) Decimal('-123')
By the way, in Python 3.x, math.ceil works exactly the way you want, except that it returns an int instance, not a Decimal . This works because math.ceil is overloaded for custom types in Python 3. In Python 2, math.ceil first converts the Decimal instance to float , potentially losing information in this process, so that you may end up with incorrect results.
Mark dickinson
source share