#------------------------------------------------------------------------------ # DecimalRounding.py # # Illustrate the quantize function in the decimal.Decimal class. See # quantize() at: https://docs.python.org/3/library/decimal.html # #------------------------------------------------------------------------------ from decimal import * def main(): N = 12 getcontext().prec = N x = Decimal('2.192853746') print() print(x) print(x.quantize(Decimal('0.000'))) # 3 digits to the right of the '.' print(x.quantize(Decimal('0E-3'))) # same thing in scientific notation print() for k in range(1,N): # try going to N+1. Observe InvalidOperation. # number of digits k must be < precision N y = Decimal('0E-'+str(k)) print(x) # number to be rounded print(y) # number giving model rounding print(x.quantize(y, rounding=ROUND_DOWN), '\t round down (truncate)') print(x.quantize(y, rounding=ROUND_UP), '\t round up') print(x.quantize(y, rounding=ROUND_HALF_DOWN), '\t round half down') print(x.quantize(y, rounding=ROUND_HALF_UP), '\t round half up') print() # end # end #------------------------------------------------------------------------------ if __name__=='__main__': main() # end