T0004 — Decimal
Part of the roadmap. Phase 1 · wave 1 · size M.
Goal
An exact, precision-preserving Decimal without dependencies (design notes, ADR-0005).
Scope
src/values/decimal/:- parse from literal or string text, and from
number(shortest round-trip) toString()that keeps the scaleadd,subtract,multiply,divide(28 significant digits, at least 8 fractional digits, trailing zeros removed, empty on division by zero)div,mod,negate,abs,round(precision)(half away from zero),truncate,floor,ceilingcompare,equals(trailing zeros ignored),equivalent(rounded to the less precise operand)- conversion to and from Integer
sqrt,exp,ln,logandpower:- non-negative integer exponents are exact
- negative integer exponents use reciprocal Decimal division (28 significant digits; a zero base gives empty)
- other exponents go through
number, rounded to 15 significant digits
- parse from literal or string text, and from
- Property-based tests (
fast-check) againstdecimal.js, which is a dev dependency only.
Design notes
Decision (ADR-0005): Callis implements its own Decimal, backed by BigInt, with no dependency.
class Decimal { // immutablereadonly coefficient: bigint; // value = coefficient × 10^-scalereadonly scale: number; // number of digits after the decimal point, ≥ 0}
Interface (src/values/decimal/; not exported from index.ts yet, T0025 decides the public API). undefined means an empty result.
// decimal.tsconst MAX_DECIMAL_DIGITS = 10_000; // the size bound, see belowfunction isWithinDecimalBounds(coefficient: bigint, scale: number): boolean;class Decimal {static readonly ZERO: Decimal;static readonly ONE: Decimal;static of(coefficient: bigint, scale?: number): Decimal; // also for Long (phase 2) and generated tablesstatic parse(text: string): Decimal | undefined; // (+|-)?\d+(.\d+)?, keeps the scale; undefined beyond the boundstatic fromNumber(value: number): Decimal | undefined; // shortest round-trip; undefined for NaN/±Infinitystatic fromInteger(value: number): Decimal; // implicit Integer → Decimalsign(): -1 | 0 | 1;isInteger(): boolean; // 2.00 istoString(): string; // keeps the scale, never exponent notationtoNumber(): number; // nearest number, for Math.* and plain outputtoInteger(): number | undefined; // whole values in the 32-bit Integer rangeadd(other: Decimal): Decimal | undefined; // undefined beyond the size boundsubtract(other: Decimal): Decimal | undefined;multiply(other: Decimal): Decimal | undefined;divide(divisor: Decimal): Decimal | undefined;div(divisor: Decimal): Decimal | undefined;mod(divisor: Decimal): Decimal | undefined;negate(): Decimal;abs(): Decimal;round(precision?: number): Decimal;truncate(): Decimal; // truncate, floor and ceiling have scale 0;floor(): Decimal; // the math functions convert them withceiling(): Decimal; // toInteger(), Quantity keeps the Decimalcompare(other: Decimal): -1 | 0 | 1;equals(other: Decimal): boolean;equivalent(other: Decimal): boolean;}// math.tsfunction sqrt(value: Decimal): Decimal | undefined;function exp(value: Decimal): Decimal | undefined;function ln(value: Decimal): Decimal | undefined;function log(value: Decimal, base: Decimal): Decimal | undefined;function power(base: Decimal, exponent: Decimal): Decimal | undefined;
of, fromInteger and round throw FhirPathEvaluationError with the code eval/invalid-argument when an argument breaks their contract (a negative or fractional scale or precision, a fractional Integer, or for of a value beyond the size bound). The function layer (T0016) should check round()'s precision itself, so the error carries the expression's span.
Requirements (N1 §4.1.4): at least 28 digits with 8 decimal places, a fixed-precision representation, and visible precision: 1.0.toString() is '1.0', and ~ and phase 2's precision()/lowBoundary() depend on the scale. A JavaScript number fails all of these (0.1 + 0.2, losing 1.0, the 2^53 limit).
Size bound (owner decision on #47): a Decimal's coefficient has at most 10,000 digits and its scale is at most 10,000 (MAX_DECIMAL_DIGITS). An operation whose exact result is beyond that is overflow or underflow and gives empty (3.0.0 §6.6), so +, - and * return Decimal | undefined like /. Without the bound, repeated multiplication doubles the digits each time until the runtime throws a bare RangeError. mod, round, truncate, floor, ceiling, abs and negate cannot leave the bound. Text beyond it does not parse, which includes number literals the lexer accepts. The compiler treats such a Decimal literal as an invalid literal value, raising eval/invalid-literal when it is evaluated (#69, T0008). Decimal.of throws (spec notes).
Semantics
+and-are exact, with scalemax(a.scale, b.scale).*is exact, with scalea.scale + b.scale. Each is empty beyond the size bound:1e9999 + 1e-10000would need 20,000 digits./always returns a Decimal (N1 §6.6.2). The quotient is computed to 28 significant digits (at least 8 fractional digits), rounded half away from zero, and trailing zeros are removed (4 / 2is2). Division by zero returns empty, and so does a quotient whose 28 significant digits or 8 digits after the point do not fit the size bound (1 / 3e9980,1e9995 / 3).div,mod,round,truncate,floor,ceilingandabsare exact.divtruncates towards zero and has scale 0;modhas the sign of the dividend and scalemax(a.scale, b.scale)(-5.5 div 2 = -2,-5.5 mod 2 = -1.5, as in the test suite).round()rounds half away from zero (0.5 → 1,-0.5 → -1), as clarified in 3.0.0. It never adds digits:1.5.round(3)is1.5(spec notes).sqrt,exp, andpowerwith a non-integer exponent go throughnumberandMath.*: the input is rounded to the nearestnumber, and the result is rounded to 15 significant digits, with trailing zeros removed. This precision loss is documented.lnandlogalso useMath.*and round the result to 15 significant digits, but they never roundxitself to a number, which would lose most of the digits near 1 and everything beyond thenumberrange. Within 1e-20 of 1 they useln(1 + d) = d; within 0.5 of 1,Math.log1pon the exactd = x − 1; beyond thenumberrange,ln(m) + k × ln(10)forx = m × 10^k. So they keep 15 significant digits over the whole Decimal range. A result beyond the size bound (log(10, 1 − 1e-10000)) is empty and is rejected before its power of ten is built.- For all five,
NaN, infinite results and underflow to zero give empty (spec notes). powerwith an integer exponent (an exponent such as2.0counts as an integer):- With a non-negative exponent the result is exact (repeated multiplication on
BigInt). If the exact power|x|^|n|is beyond the size bound (10.power(10000), or0.1.power(10001)by its scale), it is empty; for a negative exponent the bound applies to that denominator. A cheap estimate rejects huge powers before they are computed. - With a negative exponent the result cannot always be exact (
3.power(-1)is 1/3). It is computed as the reciprocal1 / x^|n|using Decimal division: 28 significant digits, trailing zeros removed, and an empty result whenxis zero (0.power(-1)is empty, like division by zero).
- With a non-negative exponent the result is exact (repeated multiplication on
- Comparison aligns scales. Literals and parsed values keep their scale.
- Equivalence rounds both values half away from zero to the precision of the less precise one, ignoring trailing zeros (spec notes).
- A
numberfromJSON.parseis converted through its shortest round-trip string. The original precision is already lost at that point, which is why T0018: lossless decimals offers a lossless JSON parser. - The tests include property-based checks against
decimal.js, used only as a dev-time oracle.
Acceptance criteria
-
1.0.toString() = '1.0',0.1 + 0.2 = 0.3,1.2 * 1.8 = 2.16,(1.2 / 1.8).round(2) = 0.67,1 / 2 = 0.5, and(-0.5).round() = -1(3.0.0). -
2.power(3) = 8and2.5.power(2) = 6.25are exact,2.power(-1) = 0.5,3.power(-1)gives 28 significant digits, and0.power(-1)is empty. - Property tests pass for add, subtract, multiply, divide and compare against the oracle (at least 1,000 runs each).
- No runtime dependency. Line coverage of
decimal/is at least 95%.