num
Exact decimal arithmetic for money, prices, quantities and anything else that has to add up to the cent, plus integer helpers (gcd, lcm, pow_mod). A Dec is an arbitrary-precision integer coefficient with a decimal scale. + - * are always exact and never overflow. Only division and rounding drop digits, and they use the rounding mode you pick. Cross-checked against Python's decimal module.
Effects: none.
fn main(): int! {
let price = num.dec("19.99")?
let qty = num.from_int(3)
let rate = num.dec("0.0825")? // sales tax
let subtotal = price * qty // 59.97
let tax = num.round(subtotal * rate, 2) // 4.947525 -> 4.95 (half-even)
let total = subtotal + tax
print("{subtotal} + {tax} = {total}") // 59.97 + 4.95 = 64.92
assert num.dec("0.1")? + num.dec("0.2")? == num.dec("0.3")? // exact, unlike float
let share = num.div(total, num.from_int(4), 2, num.Down) // 16.23
let cents = num.to_int(num.round(total, 2) * num.from_int(100))? // 6492, for storage
print(num.scaled(cents, 2)) // 64.92
print(num.dec("2.5")? / num.dec("3")?) // 0.833333333333333333
print(num.pow_mod(4, 13, 497)) // 445
0
}
API
Types:
struct Dec { neg, mag, scale }: the value±coefficient / 10^scale, wheremagholds the coefficient as base-10^9 limbs. Create values with the functions below, not by hand.enum Round { HalfEven, HalfUp, HalfDown, Down, Up, Floor, Ceiling }:HalfEvenis banker's rounding, where ties go to the even digit.HalfUpandHalfDownsend ties away from zero and toward zero.Downtruncates toward zero, andUprounds away from zero.FloorandCeilinground toward -∞ and +∞.enum NumErr { BadChar(at: int, c: char), NoDigits, ExpRange(at: int), Overflow }, andmessage(e): str.
Making and reading:
dec(s): Dec!NumErr:"19.99","-0.50",".5","5.","1.5e3","2E-4". The scale is the number of fraction digits as written, sodec("1.50")keeps two places. It accepts no spaces,_,,,infornan. Exponents are limited to ±MAX_EXP(1000).from_int(n): Dec(exact for everyint),scaled(coef, scale): Dec(scaled(1999, 2)is19.99),ZEROshow(d), i.e."{d}": plain digits that keep the scale (19.90,-0.005,1000). There's no exponent and no grouping.to_int(d): int!NumErrtruncates toward zero and fails withOverflowoutside the 64-bit range.to_float(d): floatgives the nearest float.sign(d)(-1, 0 or 1),is_zero(d),neg(d),abs(d),normalize(d)(drops trailing fraction zeros:1.500→1.5)
Arithmetic (the operators come from add, sub, mul, div, mod, cmp and eq):
a + b,a - b: exact. The result has the larger of the two scales.a * b: exact. The scales add (1.5 * 2.25 == 3.375), soroundit back to cents.div(a, b, places, mode): Dec: the quotient with exactlyplacesfraction digits. This is the one to use for money.a / b: computed toDIV_PLACES(18) fraction digits with half-even rounding. Trailing zeros are then dropped down to the larger input scale, so10.00 / 4 == 2.50and1 / 8 == 0.125, but1 / 3 == 0.333333333333333333.a % b: the remainder of truncating division, with the sign ofa(as%works onint).round(d, places)(half-even) andround(d, places, mode): exactlyplacesdigits. Asking for more places thandhas pads it with zeros.pow(d, n)(exact,n >= 0),sum(xs: [Dec])(core'sxs.sum()covers onlyintandfloat)==,<,sort,min,max: numeric order that ignores scale, sodec("1.5") == dec("1.50").
Integers:
gcd(a, b)(always >= 0, andgcd(0, 0) == 0),lcm(a, b)(always >= 0, and 0 if either argument is 0)pow_mod(base, exp, m)andmul_mod(a, b, m): results in0..m. A negativebaseis reduced first. Neither function overflows for anym > 0: products of large values go through an add-and-double loop.
Range and overflow
Decnever overflows. The coefficient grows as needed:9223372036854775807 + 1is9223372036854775808, and2^100is exact. Each operation's cost grows with its digit count, and the code is tuned for money-sized values (up to a few dozen digits). Division of very long numbers, thousands of digits, is slow but correct.- The 64-bit limit applies only where a
Decbecomes anint:to_intreturnsErr(Overflow)instead of wrapping.scaledandfrom_inttake anyint. - Parsing is bounded: exponents beyond ±1000 are rejected (
ExpRange), so a short string like1e999999999can't allocate a billion digits. - Division by zero in
/,%ordivfails a contract (a panic), as withint. inthelpers trap likeintdoes:lcmpanics if the result exceeds 2^63 - 1, andgcddoes so only forgcd(int.MIN, 0)andgcd(int.MIN, int.MIN), whose answer is 2^63.pow_modandmul_modnever overflow.
Notes
==is numeric, but the hash used by maps anduniquestill sees the scale. Normalize values before you use them as keys:m[num.normalize(price)] = ….- Unary minus can't be overloaded in Auk, so write
x.neg()ornum.ZERO - x. to_value/from_value(and sojson.encode/decode) use the derived struct form{"neg", "mag", "scale"}. For a readable JSON field, store"{d}"as astrandnum.decit back.Bigintegers (planned) would reuse the same limb arithmetic. They aren't in 0.1.