Rounding and Formatting
round() — round to decimal places
var x = Decimal("123.456")
print(x.round(2)) # 123.46 (ROUND_HALF_EVEN)
print(x.round(1)) # 123.5
print(x.round(0)) # 123
print(x.round(-1)) # 1.2E+2
print(x.round(2, ROUND_DOWN)) # 123.45
print(x.round(2, ROUND_UP)) # 123.46
Also works with round() builtin:
print(round(Decimal("123.456"), 2)) # 123.46
quantize() — match scale of another decimal
Adjusts the scale (number of decimal places) to match the scale of exp. The
actual value of exp is ignored — only its scale matters.
var x = Decimal("1.2345")
print(x.quantize(Decimal("0.01"))) # 1.23 (2 decimal places)
print(x.quantize(Decimal("0.1"))) # 1.2 (1 decimal place)
print(x.quantize(Decimal("1"))) # 1 (0 decimal places)
# Currency formatting:
var price = Decimal("19.999")
print(price.quantize(Decimal("0.01"))) # 20.00
normalize() — remove trailing zeros
print(Decimal("1.2345000").normalize()) # 1.2345
__ceil__, __floor__, __trunc__
print(Decimal("1.1").__ceil__()) # 2
print(Decimal("1.9").__floor__()) # 1
print(Decimal("-1.9").__trunc__()) # -1