The Decimal type provides exact decimal arithmetic backed by java.math.BigDecimal. Use it instead of Float when rounding errors are unacceptable (financial calculations, invoices, rates).
from decimal import parse, from_int, round_half_up
let price = parse("19.99").unwrap()
let qty = from_int(3)
let total = price * qty # 59.97 (exact)
let tax = total.divide(from_int(100), 2, round_half_up)
| Function | Returns | Description |
|---|---|---|
parse(s) | Result[Decimal, DecimalError] | Parse a string into a Decimal |
from_int(n) | Decimal | Create a Decimal from an integer |
from_float(n) | Decimal | Create from float (prefer parse for exact values) |
Decimal supports +, -, *, and comparison operators (==, !=, <, >, <=, >=).
Division requires explicit scale and rounding mode:
let result = a.divide(b, scale, mode)
let rounded = d.quantize(scale, mode)
| Constant | Description |
|---|---|
round_half_up | Rounds 0.5 away from zero; for invoices |
round_half_even | Banker's rounding; minimizes bias |
round_down | Truncate toward zero; never exceeds |
round_up | Round away from zero; never undershoots |