Getting Ceil () of a decimal in python?

Is there a way to get the upper limit of decimal precision in python?

>>> import decimal; >>> decimal.Decimal(800000000000000000001)/100000000000000000000 Decimal('8.00000000000000000001') >>> math.ceil(decimal.Decimal(800000000000000000001)/100000000000000000000) 8.0 

math rounds the value and returns an inaccurate value

+6
source share
6 answers
 x = decimal.Decimal('8.00000000000000000000001') with decimal.localcontext() as ctx: ctx.prec=100000000000000000 ctx.rounding=decimal.ROUND_CEILING y = x.to_integral_exact() 
+5
source

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.

+18
source

You can do this using the precision and rounding options in the context constructor.

 ctx = decimal.Context(prec=1, rounding=decimal.ROUND_CEILING) ctx.divide(decimal.Decimal(800000000000000000001), decimal.Decimal(100000000000000000000)) 

EDIT: You should consider changing the accepted answer. Although prec can be increased as needed, to_integral_exact is a simpler solution.

+3
source
 >>> decimal.Context(rounding=decimal.ROUND_CEILING).quantize( ... decimal.Decimal(800000000000000000001)/100000000000000000000, 0) Decimal('9') 
0
source
 def decimal_ceil(x): int_x = int(x) if x - int_x == 0: return int_x return int_x + 1 
0
source

Just use potency to do this. import math

 def lo_ceil(num, potency=0): # Use 0 for multiples of 1, 1 for multiples of 10, 2 for 100 ... n = num / (10.0 ** potency) c = math.ceil(n) return c * (10.0 ** potency) lo_ceil(8.0000001, 1) # return 10 
0
source

All Articles