decimal

    Arbitrary-precision decimal arithmetic for MoonBit

    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    17 days ago
    Downloads
    23

    No dependencies

    #decimal

    Arbitrary-precision decimal arithmetic for MoonBit.

    mooncakes.io MoonBit library License: Apache-2.0

    #Overview

    moonbit-community/decimal is an arbitrary-precision decimal arithmetic library for MoonBit. It implements the General Decimal Arithmetic specification (v1.70, Mike Cowlishaw / IBM — the decimal arithmetic of IEEE 754-2008): base-10 arithmetic with exact representation of decimal fractions, correct rounding, and the full set of status flags and special values (+0/-0, +/-Infinity, quiet NaN, and signaling NaN).

    Unlike binary floating point, 0.1 + 0.2 is exactly 0.3. Each context-aware operation takes an explicit Context (precision, rounding mode, exponent bounds) and returns its result paired with the status Flags it raised — no hidden mutable state — so arithmetic is deterministic and the same code can target decimal32, decimal64, decimal128, or an unbounded exact context. For quick math, the + - * / operators work directly under a fixed default context.

    #Installation

    Add the module from the MoonBit registry:

    moon add moonbit-community/decimal

    Then import it from your package manifest:

    import {
    "moonbit-community/decimal",
    }

    #Examples

    let a = @decimal.Decimal::parse("0.1")
    let b = @decimal.Decimal::parse("0.2")

    // Operators evaluate under a fixed default context — handy for quick math.
    println(a + b) // 0.3 (exact, not 0.30000000000000004)

    // The explicit-context methods return the result *and* the flags they raised.
    let ctx = @decimal.Context::decimal64()
    let (sum, flags) = a.add(b, ctx)
    println(sum) // 0.3
    println(flags.inexact) // false

    // Money: round a product to two fractional digits.
    let price = @decimal.Decimal::parse("19.99")
    let qty = @decimal.Decimal::from_int(3)
    let (subtotal, _) = price.multiply(qty, ctx)
    let (total, _) = subtotal.quantize(@decimal.Decimal::parse("0.01"), ctx)
    println(total) // 59.97

    #Operations

    Each context-aware method takes a Context as the final argument and returns (Decimal, Flags) — the result paired with the status flags that computation raised (Flags::combine folds them across a sequence). The + - * / and unary - operators are conveniences over these, evaluated under a fixed decimal128 context with a fresh flag set per call.

    • Arithmetic: add subtract multiply divide divide_int remainder fma abs minus plus
    • Comparison: compare compare_signal compare_total compare_total_magnitude max min max_magnitude min_magnitude same_quantum
    • Rounding / scaling: quantize rescale reduce scaleb to_integral_value to_integral_exact finalize
    • Exponent / digits: shift rotate next_plus next_minus next_toward
    • Logical (digit-wise on 0/1 strings): logical_and logical_or logical_xor logical_invert
    • Mathematical (correctly rounded): sqrt exp ln log10 power
    • Copy / sign (no rounding): copy copy_abs copy_negate copy_sign canonical
    • Classification: is_finite is_infinite is_nan is_signaling is_zero is_normal is_subnormal is_canonical number_class

    See src/pkg.generated.mbti for the full signatures.

    #Conversions

    Convert between Decimal and the machine numeric types:

    • From strings: parse(s) (exact; raises ParseError on bad input) and from_string(s, ctx) (GDA to-number: rounds to the context and returns (Decimal, Flags), yielding NaN with conversion_syntax set on bad input)
    • From (exact, total): from_int from_int64 from_bigint from_double
    • To integer (partial — None for non-finite, non-integer, or out-of-range values, never a silent truncation): to_int to_int64 to_bigint
    • To Double (total but lossy; saturates to +/-Infinity past range): to_double
    • To String: to_sci_string (GDA to-scientific-string, also the Show rendering) and to_eng_string (engineering notation, exponent a multiple of three)

    Decimal implements Eq, Compare, and Hash by numeric value, so values sort, dedupe, and serve as map keys directly: 1.0 and 1.00 compare and hash equal, -0 equals +0, and NaN sorts below everything. For the specification's signalling, cohort-distinguishing comparisons use the explicit compare / compare_signal / compare_total methods.

    from_double keeps the double's exact binary value in canonical form, so from_double(0.1) is 0.1000000000000000055511151231257827021181583404541015625. For the short, human-facing form, parse the rendered string instead: Decimal::parse(d.to_string()). To narrow a non-integer to an integer, round first with to_integral_value / to_integral_exact.

    To build a value with an explicit exponent (a coefficient × 10ᵉ), use try_finite(coef, exp, negative?) -> Decimal? (e.g. try_finite(150N, -2) is 1.50; None if the coefficient is negative — the sign lives in negative), or unsafe_finite when you already uphold that invariant.

    Decimal also implements ToJson / @json.FromJson, serializing as the GDA string so values round-trip exactly (JSON numbers are binary64 and would lose precision).

    #Interchange Encoding

    IEEE 754 / GDA decimal interchange encodings are available as uppercase network-byte-order hexadecimal strings:

    • Decode: from_decimal32_hex from_decimal64_hex from_decimal128_hex
    • Encode: to_decimal32_hex to_decimal64_hex to_decimal128_hex

    Encoding returns (hex, Flags) after rounding/clamping into the selected format. Decoding is exact and returns None for malformed hex strings.

    #Tests

    The operation tests under src/tests/ embed the IBM .decTest conformance corpora.

    # Run the full test suite moon test # Control parallelism moon test -j 8 # Run tests for one operation package moon test src/tests/divide # Run tests from one file moon test src/tests/parse/parse_test.mbt

    Microbenchmarks (small/large arithmetic, conversion, format, math functions) live in src/tests/benchmarks/:

    moon bench -p moonbit-community/decimal/tests/benchmarks

    #Development

    A Nix flake provides a dev shell with the MoonBit toolchain and a C compiler:

    nix develop # or: direnv allow moon check

    Without Nix, install the MoonBit toolchain directly and run the same moon commands.

    #Layout

    PathContents
    src/the library (one file per operation family)
    src/dectest/the .decTest parser/runner harness (no test data)
    src/tests/per-operation packages embedding the IBM corpora

    #License

    Apache-2.0. See LICENSE.

    ParseError

    pub(all) suberror ParseError {
    Empty
    ExpectedDigit(position~ : Int)
    InvalidExponent(position~ : Int)
    TrailingGarbage(position~ : Int)
    BadKeyword(position~ : Int)
    } derive(Eq)

    Errors raised by Decimal::parse.
    impl Show for ParseError

    ParseError::equal

    fn ParseError::equal(ParseError, ParseError) -> Bool

    ParseError::not_equal

    fn ParseError::not_equal(x : ParseError, y : ParseError) -> Bool

    ParseError::output

    fn ParseError::output(self : ParseError, logger : &Logger) -> Unit

    ParseError::to_string

    fn ParseError::to_string(self : ParseError) -> String

    Class

    pub(all) enum Class {
    Finite
    Infinity
    QNaN
    SNaN
    } derive(Eq,
    Debug
    )

    Classification of a Decimal value, following the General Decimal Arithmetic specification (Cowlishaw / IEEE 754-2008 decimal).
    impl Show for Class

    Class::equal

    fn Class::equal(Class, Class) -> Bool

    Class::not_equal

    fn Class::not_equal(x : Class, y : Class) -> Bool

    Class::output

    fn Class::output(self : Class, logger : &Logger) -> Unit

    Class::to_repr

    Class::to_string

    fn Class::to_string(self : Class) -> String

    Context

    pub struct Context {
    precision : Int
    rounding : Rounding
    e_min : Int
    e_max : Int
    clamp : Bool
    flags : Flags
    }

    Arithmetic context — precision, rounding mode, and exponent range.

    Context is immutable configuration: operations take a Context, never mutate it, and return their result paired with the Flags they raised. (The flags field below is a per-call scratch accumulator; a caller's own Context value is never written to.)

    precision == 0 means "no precision limit": the op produces an exact result with as many digits as needed. This is the default so the existing "exact" arithmetic surface keeps its current behaviour.

    Context::decimal128

    fn Context::decimal128() -> Context

    IEEE-754 decimal128 preset: precision 34, Emax = 6144, Emin = -6143, clamp = true.

    Context::decimal32

    fn Context::decimal32() -> Context

    IEEE-754 decimal32 preset: precision 7, Emax = 96, Emin = -95, clamp = true, rounding half-even.

    Context::decimal64

    fn Context::decimal64() -> Context

    IEEE-754 decimal64 preset: precision 16, Emax = 384, Emin = -383, clamp = true.

    Context::exact

    fn Context::exact() -> Context

    Convenience: a context that performs no rounding and lets every result pass through exactly. Mostly useful as a sentinel for "give me exact arithmetic" callers.

    Context::new

    fn Context::new(precision? : Int, rounding? : Rounding, e_min? : Int, e_max? : Int, clamp? : Bool) -> Context

    Build a Context. Defaults: no precision cap, half-to-even rounding, near-Int.max exponent range (effectively unbounded for dectest's range), no clamp.

    Panics if precision < 0 or e_min > e_max — these are API-misuse (typically literal typos), so they fail fast rather than returning an error.

    Decimal

    pub struct Decimal {
    class : Class
    negative : Bool
    coefficient :
    BigInt

    exponent : Int
    }

    Arbitrary-precision signed decimal value, per the General Decimal Arithmetic specification.

    For class = Finite, the numeric value is (-1)^negative * coefficient * 10^exponent.

    For class = Infinity, only negative is meaningful.

    For class = QNaN / SNaN, coefficient carries the diagnostic payload (zero if none was specified) and negative carries the sign.

    coefficient is always non-negative; the sign lives in negative so that -0, -Infinity and -NaN round-trip distinctly.
    impl Add for Decimal
    impl Compare for Decimal
    impl Div for Decimal
    impl Eq for Decimal
    impl Hash for Decimal
    impl Mul for Decimal
    impl Neg for Decimal
    impl Show for Decimal
    impl Sub for Decimal
    impl ToJson for Decimal
    impl FromJson for Decimal

    Decimal::abs

    fn Decimal::abs(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA abs: |N| under the context — minus when the sign bit is set, otherwise plus. NaN propagation wins over the absolute value, so a NaN's sign is not cleared (e.g. abs(-NaN22) = -NaN22); a signaling NaN raises Invalid_operation.

    Decimal::add

    fn Decimal::add(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA add: arithmetic addition.

    • sNaN in either operand: result is the sNaN with class quietened to QNaN. sNaN at position 0 wins over sNaN at position 1 (and over any QNaN).
    • QNaN propagation: if no sNaN, the first NaN (left-to-right) wins, with its sign and payload preserved.
    • Same-sign infinities: same-sign infinity returned.
    • Opposite-sign infinities: +Infinity + -Infinity = NaN (the Invalid_operation signal is raised).
    • Infinity + finite: the infinity.
    • Finite + finite: exact sum at the smaller operand exponent, then context finalization.
    • Sign of a zero result: same sign when both operands share a sign, -0 under Floor when signs differ, +0 otherwise.

    Decimal::canonical

    fn Decimal::canonical(self : Decimal) -> Decimal

    GDA canonical: returns the canonical form of self. For this library every value is already canonical, so this is the identity — kept for API completeness alongside is-canonical.

    Decimal::compare

    fn Decimal::compare(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA compare: numeric comparison returning -1, 0, or 1 as a Decimal. Distinct from compare-total in that NaN operands propagate (compare-total wraps NaN into the total order) and values that are numerically equal but differ in scale (e.g. 1 vs 1.0) return 0.

    sNaN in either operand: signals Invalid_operation and returns the quietened sNaN. QNaN: propagates per the usual left-to-right rule.

    For infinities: -Infinity < every finite < +Infinity. Two infinities of the same sign are equal; opposite signs use the sign rule.

    Decimal::compare_signal

    fn Decimal::compare_signal(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA compare-signal: numerically compare like compare, but signal Invalid_operation on any NaN operand — quiet NaNs are treated as signaling.

    Decimal::compare_total

    fn Decimal::compare_total(self : Decimal, other : Decimal) -> Decimal

    GDA compare-total: total ordering across every Decimal value, including NaNs. Returns -1, 0, or 1 as a Decimal.

    Ordering, from smallest to largest:

    -NaN(p) ... < -sNaN(p) ... < -Infinity < -finite ... < +0 = -0 (per numerical value, broken by exponent) ... +finite < +Infinity < +sNaN(p) ... < +NaN(p) ...

    For numerically-equal finites with different exponents, the operand with the smaller exponent sorts first — regardless of sign. This is GDA's sign-independent tie-break rule.

    Decimal::compare_total_magnitude

    fn Decimal::compare_total_magnitude(self : Decimal, other : Decimal) -> Decimal

    GDA compare-total-magnitude: compare-total applied to |self| and |other|. Sign-stripping happens via copy_abs, which clears the sign bit even on NaN.

    Decimal::copy

    fn Decimal::copy(self : Decimal) -> Decimal

    GDA copy: structural identity. The operand is returned unchanged. The op exists in the spec so that copy(sNaN) round-trips as sNaN instead of being quietened — a property no arithmetic op offers.

    Decimal::copy_abs

    fn Decimal::copy_abs(self : Decimal) -> Decimal

    GDA copyAbs: clear the sign bit. Unlike abs, the sign of NaN is cleared too (copyAbs(-NaN10) = NaN10).

    Decimal::copy_negate

    fn Decimal::copy_negate(self : Decimal) -> Decimal

    GDA copyNegate: flip the sign bit. Unlike minus, the sign of NaN is flipped too and zero stays signed.

    Decimal::copy_sign

    fn Decimal::copy_sign(self : Decimal, other : Decimal) -> Decimal

    GDA copySign: take everything from self except the sign bit, which comes from other.

    Decimal::div

    fn Decimal::div(self : Decimal, other : Decimal) -> Decimal

    Decimal::divide

    fn Decimal::divide(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA divide: true division with precision-driven rounding. The result has precision digits (before final rounding) and an exponent chosen so that the value is (a / b) to within half a ULP under the active rounding mode.

    Special values follow the usual NaN / Infinity propagation rules:
    • Infinity / Infinity → NaN (Invalid_operation).
    • Infinity / finite-nonzero → ±Infinity (XOR sign).
    • finite / Infinity → ±0 (XOR sign).
    • 0 / x (x ≠ 0) → signed 0 with ideal_exp = a.exp - b.exp.
    • x / 0 (x ≠ 0) → ±Infinity (Division_by_zero raised).
    • 0 / 0 → NaN (Division_undefined raised).

    Precision is required: when ctx.precision == 0 and the division is not exact, the result is NaN with Invalid_operation raised — there's no stopping criterion for a non-terminating decimal (e.g. 1/3).

    Decimal::divide_int

    fn Decimal::divide_int(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA divide-integer: truncated integer quotient trunc(a / b).

    • Special values follow the usual NaN / Infinity propagation rules.
    • 0 / 0 raises Division_undefined; Infinity / Infinity raises Invalid_operation.
    • finite / 0 (with finite ≠ 0) and Infinity / 0 give a signed Infinity; finite non-zero divided by zero raises Division_by_zero.
    • finite / Infinity is a signed zero.
    • Result exponent for the finite/finite case is 0: the quotient is by definition an integer.
    • If the finite quotient exceeds the active precision, Division_impossible is raised and the result is NaN.

    Decimal::equal

    fn Decimal::equal(self : Decimal, other : Decimal) -> Bool

    Decimal::exp

    fn Decimal::exp(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA exp: e raised to the operand.

    Decimal::finalize

    fn Decimal::finalize(self : Decimal, ctx : Context) -> (Decimal, Flags)

    Finalize self under ctx — round to precision and enforce the exponent range — returning the result paired with the Flags it raised. See finalize_raw for the algorithm.

    Decimal::fma

    fn Decimal::fma(self : Decimal, other : Decimal, addend : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA fused-multiply-add: (self * other) + addend with a single rounding at the final addition. Equivalent to running the multiply at unbounded precision, then re-finalising the sum under the caller's context — so the precision-bounded product never loses digits that would have been recovered by the subsequent add.

    NaN propagation runs as a single left-to-right scan over all three operands: the leftmost signaling NaN wins outright (raising Invalid_operation), regardless of position — a signaling addend beats a quiet multiplicand. With no signaling NaN, a quiet NaN in a multiplicand propagates (leftmost first). Only once both multiplicands are non-NaN does the actual (self * other) + addend run, where multiply signals 0 * Infinity and add signals ±Infinity + ∓Infinity and propagates a quiet-NaN addend.

    The product is formed at unbounded precision so the precision-bounded result never loses digits the subsequent add would have recovered.

    Decimal::from_bigint

    Lift a BigInt into a Decimal at exponent 0.

    Decimal::from_decimal128_hex

    fn Decimal::from_decimal128_hex(hex : String) -> Decimal?

    Decode a decimal128 DPD interchange payload from network-byte-order hexadecimal. Returns None if the string is not exactly 32 hex digits.

    Decimal::from_decimal32_hex

    fn Decimal::from_decimal32_hex(hex : String) -> Decimal?

    Decode a decimal32 DPD interchange payload from network-byte-order hexadecimal. Returns None if the string is not exactly 8 hex digits.

    Decimal::from_decimal64_hex

    fn Decimal::from_decimal64_hex(hex : String) -> Decimal?

    Decode a decimal64 DPD interchange payload from network-byte-order hexadecimal. Returns None if the string is not exactly 16 hex digits.

    Decimal::from_double

    fn Decimal::from_double(x : Double) -> Decimal

    Convert a binary64 Double into the Decimal carrying its exact value.

    A finite double is a binary fraction ±mantissa × 2^e, which has an exact finite decimal expansion — so the result is faithful, not rounded: from_double(0.1) is 0.1000000000000000055511151231257827021181583404541015625, the value 0.1 actually denotes in binary64. (For the short, human-facing form instead, parse the rendered string: Decimal::parse(d.to_string()).)

    NaN and ±Infinity map to the corresponding decimal specials.

    Decimal::from_int

    fn Decimal::from_int(n : Int) -> Decimal

    Lift an Int into a Decimal at exponent 0.

    Decimal::from_int64

    fn Decimal::from_int64(n : Int64) -> Decimal

    Lift an Int64 into a Decimal at exponent 0. Exact and total.

    Decimal::from_string

    fn Decimal::from_string(s : String, ctx : Context) -> (Decimal, Flags)

    GDA to-number: convert a string to a Decimal under a context, returning the result paired with the Flags raised. This is the flag-based companion to parse: on a malformed string it returns a quiet NaN and raises conversion_syntax (rather than raising ParseError); on a valid string it rounds the parsed value to the context and reports any inexact / rounded / range flags. Use parse when a syntax error should be a catchable ParseError; use this when you want GDA's NaN-plus-conversion_syntax behaviour.

    Decimal::hash

    fn Decimal::hash(self : Decimal) -> Int

    Decimal::hash_combine

    fn Decimal::hash_combine(self : Decimal, hasher : Hasher) -> Unit

    Decimal::infinity

    fn Decimal::infinity() -> Decimal

    +Infinity.

    Decimal::is_canonical

    fn Decimal::is_canonical(_self : Decimal) -> Bool

    Every value produced by this library is canonical — we don't have the IEEE-754 DPD representation's "non-canonical" encoding to worry about, so the answer is unconditionally true. Provided for API completeness (is-canonical is one of GDA's mandatory predicates).

    Decimal::is_finite

    fn Decimal::is_finite(self : Decimal) -> Bool

    Predicates.

    Decimal::is_infinite

    fn Decimal::is_infinite(self : Decimal) -> Bool

    Decimal::is_nan

    fn Decimal::is_nan(self : Decimal) -> Bool

    Decimal::is_normal

    fn Decimal::is_normal(self : Decimal, ctx : Context) -> Bool

    true for non-zero finite values whose adjusted exponent is within [ctx.e_min, ctx.e_max] — i.e. the operand is representable in the "normal" range. Zero and the entire NaN / Infinity family are not normal.

    Decimal::is_signaling

    fn Decimal::is_signaling(self : Decimal) -> Bool

    Decimal::is_subnormal

    fn Decimal::is_subnormal(self : Decimal, ctx : Context) -> Bool

    true for finite non-zero values whose adjusted exponent is below ctx.e_min — i.e. the operand is representable but in the gradual- underflow region. is_normal and is_subnormal partition the finite-non-zero values.

    Decimal::is_zero

    fn Decimal::is_zero(self : Decimal) -> Bool

    true for finite zero (sign-independent: 0 and -0 both qualify).

    Decimal::ln

    fn Decimal::ln(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA ln: natural logarithm. ln(1) = 0; ln(x) for finite x > 0 uses the atanh series plus range reduction; ln(0) = -Infinity (with Division_by_zero raised); ln of negative or NaN is the usual propagation / invalid.

    Decimal::log10

    fn Decimal::log10(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA log10: common (base-10) logarithm. Built as ln(x) / ln(10) at workp precision; falls back to the closed-form result for exact powers of ten.

    Decimal::logical_and

    fn Decimal::logical_and(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA logical-and: digit-wise AND of two bit-string Decimals.

    Decimal::logical_invert

    fn Decimal::logical_invert(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA logical-invert: digit-wise NOT, width set by ctx.precision (or the operand's natural width when precision is 0). Unlike the binary ops, invert needs the operand to be left-padded to the full precision width — otherwise invert(10) at precision 9 would render as 01 rather than 111111101.

    Decimal::logical_or

    fn Decimal::logical_or(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA logical-or: digit-wise OR.

    Decimal::logical_xor

    fn Decimal::logical_xor(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA logical-xor: digit-wise XOR.

    Decimal::max

    fn Decimal::max(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA max: numeric maximum.

    Picks the larger operand; on a numerical tie GDA's sign / exponent rule applies (positive over negative; if same sign, larger exponent for the positive chain, smaller exponent for the negative chain).

    NaN handling diverges from compare: a single quiet NaN is ignored, and max(qNaN, x) = x (with x re-finalised). A signaling NaN still signals and quietens. Both qNaN: canonical NaN returned (the left operand here).

    Decimal::max_magnitude

    fn Decimal::max_magnitude(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA max-magnitude: compare by absolute value, returning the operand whose magnitude is larger. Sign of the returned operand is preserved. On a magnitude tie the same sign / exponent rule as max applies.

    Decimal::min

    fn Decimal::min(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA min: numeric minimum. Mirrors max's sign / exponent tiebreak.

    Decimal::min_magnitude

    fn Decimal::min_magnitude(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA min-magnitude: compare by absolute value, returning the operand whose magnitude is smaller.

    Decimal::minus

    fn Decimal::minus(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA minus: subtract('0', N) applied under the context — negate the operand and round to precision, raising the usual flags (rounding → Inexact / Rounded, plus overflow / subnormal / clamp via finalize).

    NaN handling is explicit so the operand's NaN sign and payload propagate unchanged — a NaN is never arithmetically negated — while a signaling NaN raises Invalid_operation (and its payload is truncated to precision).

    Decimal::mul

    fn Decimal::mul(self : Decimal, other : Decimal) -> Decimal

    Decimal::multiply

    fn Decimal::multiply(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA multiply. Coefficients multiply, exponents add, signs XOR.

    Special values follow the usual priority: sNaN wins over QNaN (with the quieten-and-keep-sign rule); 0 * Infinity is NaN and raises Invalid_operation; finite-nonzero * Infinity yields an infinity with the XOR sign; Infinity * Infinity yields the XOR-signed Infinity.

    Decimal::nan

    fn Decimal::nan(payload? :
    BigInt
    , negative? : Bool) -> Decimal

    A quiet NaN with the given (non-negative) diagnostic payload. The no-payload, non-negative variant returns a shared singleton.

    Panics if payload is negative — the payload is stored as the (non-negative) coefficient. A negative payload is a programmer error, not untrusted input, so it fails fast rather than returning an error.

    Decimal::neg

    fn Decimal::neg(self : Decimal) -> Decimal

    Decimal::neg_infinity

    fn Decimal::neg_infinity() -> Decimal

    -Infinity.

    Decimal::next_minus

    fn Decimal::next_minus(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA next-minus: largest representable value less than self.

    Decimal::next_plus

    fn Decimal::next_plus(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA next-plus: smallest representable value greater than self.

    Decimal::next_toward

    fn Decimal::next_toward(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA next-toward: walk self one ULP toward other. When the two operands compare equal numerically, return self (with other's sign in the equal-zero case, per GDA's sign-of-zero rule for next-toward).

    Decimal::not_equal

    fn Decimal::not_equal(x : Decimal, y : Decimal) -> Bool

    Decimal::number_class

    fn Decimal::number_class(self : Decimal, ctx : Context) -> String

    GDA class: render the operand's category as one of the ten symbolic labels from §3.5: sNaN, NaN, +Infinity, -Infinity, +Normal, -Normal, +Subnormal, -Subnormal, +Zero, -Zero. The Normal / Subnormal distinction needs the active Context to know e_min.

    Named number_class rather than class because class is a field name on Decimal; the GDA op name class would clash with field access syntax.

    Decimal::one

    fn Decimal::one() -> Decimal

    The decimal +1.

    Decimal::op_ge

    fn Decimal::op_ge(x : Decimal, y : Decimal) -> Bool

    Decimal::op_gt

    fn Decimal::op_gt(x : Decimal, y : Decimal) -> Bool

    Decimal::op_le

    fn Decimal::op_le(x : Decimal, y : Decimal) -> Bool

    Decimal::op_lt

    fn Decimal::op_lt(x : Decimal, y : Decimal) -> Bool

    Decimal::output

    fn Decimal::output(self : Decimal, logger : &Logger) -> Unit

    Decimal::parse

    fn Decimal::parse(input : String) -> Decimal raise ParseError

    Parse a decimal literal, following the General Decimal Arithmetic grammar:

    numeric-string ::= [sign] numeric-value | [sign] nan numeric-value ::= decimal-part [exponent-part] | infinity decimal-part ::= digits '.' [digits] | ['.'] digits exponent-part ::= ('e' | 'E') [sign] digits infinity ::= 'Infinity' | 'Inf' -- case-insensitive nan ::= 'NaN' [digits] -- case-insensitive | 'sNaN' [digits]

    Rejects: empty input, lone ., exponent with no digits, leading/trailing whitespace, underscores. NaN payloads are parsed into Decimal.coefficient.

    Decimal::plus

    fn Decimal::plus(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA plus: add('0', N) applied under the context — round the operand to precision (value and sign preserved) and raise the usual flags. As with minus, a NaN propagates unchanged and a signaling NaN raises Invalid_operation.

    Decimal::power

    fn Decimal::power(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA power: self ^ other. Integer exponents use square-and-multiply for exactness; non-integer exponents use exp(other · ln(self)). Domain rules: power(0, 0) = 1; power(±0, neg) = ±Infinity with Division_by_zero; power(neg, non-integer) = NaN.

    Decimal::quantize

    fn Decimal::quantize(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA quantize: return a value equal to self (possibly rounded) with exponent equal to other.exponent.

    • If other.exponent < self.exponent, the coefficient is multiplied by 10^(self.exponent - other.exponent) to pad with trailing zeros.
    • If other.exponent > self.exponent, the coefficient loses the excess trailing digits under the active rounding mode; Rounded is raised (with Inexact if those digits were non-zero).

    Special-value rules: any NaN propagates per usual; two infinities give back self; mixing an infinity with a finite is Invalid_operation (cannot rescale a finite to an infinite exponent or vice versa).

    If the rescaled coefficient would have more than precision digits, the result is NaN with Invalid_operation raised — there's no representable value with that exponent at the given precision.

    Decimal::reduce

    fn Decimal::reduce(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA reduce (also known as normalize): strip trailing zeros from the coefficient, raising the exponent to compensate, so the result has the same value but the most "concise" representation.

    Zero is normalised to exponent = 0 regardless of input exponent (reduce(0E+5) = 0); sign is preserved.

    Re-finalises the result so precision rounding still applies if the stripped coefficient happens to exceed ctx.precision (unusual but possible for inputs that arrive over-wide).

    Decimal::remainder

    fn Decimal::remainder(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA remainder: a - divide_int(a, b) * b.

    The result carries a's sign (and exponent min(a.exp, b.exp) via the underlying subtract). Special cases:

    • NaN / sNaN propagate per the usual rules.
    • Infinity as dividend, or 0 as divisor: NaN.
    • Finite dividend with Infinity divisor: the dividend is returned unchanged.

    Decimal::rescale

    fn Decimal::rescale(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA rescale: like quantize, but the second operand's value (not its exponent) is the target exponent. rescale(x, 2) ≡quantize(x, 1E+2). Provided for spec completeness; quantize is the more general form.

    Decimal::rotate

    fn Decimal::rotate(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA rotate: cyclically rotate the digits of self (treated as a precision-width unsigned integer) by other positions — left for positive, right for negative. The first operand may carry any decimal digit (unlike the logical ops); only the second has the integer-in- [-precision, precision] constraint.

    Decimal::same_quantum

    fn Decimal::same_quantum(self : Decimal, other : Decimal) -> Decimal

    GDA same-quantum: returns 1 if self and other have the same exponent, 0 otherwise. Finites compare exponents directly; two infinities count as the same quantum; any two NaNs (sign-agnostic, both QNaN and SNaN) count as the same; mismatched classes return 0.

    Decimal::scaleb

    fn Decimal::scaleb(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA scaleb: shift the exponent of self by other (an integer). Equivalent to multiplying by 10^other, with the result re-finalised so overflow / underflow / clamp rules still apply.

    other must be a finite integer with |value| ≤ 2 · (e_max +precision); out-of-range yields NaN with Invalid_operation.

    Decimal::shift

    fn Decimal::shift(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA shift: shift the digits of self (precision-width) by other positions; positions shifted past either end are discarded, vacated positions are filled with zeros.

    Decimal::snan

    fn Decimal::snan(payload? :
    BigInt
    , negative? : Bool) -> Decimal

    A signaling NaN with the given (non-negative) diagnostic payload. Panics if payload is negative (a programmer error, as for nan).

    Decimal::sqrt

    fn Decimal::sqrt(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA sqrt / IEEE-754 squareRoot.

    • sqrt(NaN): propagates.
    • sqrt(+Inf): +Inf.
    • sqrt(-Inf), sqrt(-x) for non-zero finite x: NaN + Invalid_operation.
    • sqrt(±0): ±0 with the GDA "ideal exponent" floor(x.exponent / 2).
    • sqrt(finite positive): Newton-style integer sqrt, half-even rounded to precision digits.

    Decimal::sub

    fn Decimal::sub(self : Decimal, other : Decimal) -> Decimal

    Decimal::subtract

    fn Decimal::subtract(self : Decimal, other : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA subtract. NaN operands are intercepted first so the right operand's NaN is reported with its sign and payload intact (the bit-level flip below would otherwise toggle a NaN's sign bit); everything else — finite and infinity — is resolved by add after a bit-level sign flip on the second operand.

    The flip is intentionally bit-level (not Decimal::minus) because GDA's subtract zero-sign rule differs from add's: subtract(-0, 0) = -0, which would lose its sign through minus(0) = +0 followed by add(-0, +0) = +0. Flipping the sign without zero-canonicalisation makes add(-0, -0) = -0 (the same-sign-zeros rule) produce the right answer.

    Decimal::to_bigint

    The exact integer value of self as a BigInt, or None when self is not a finite integer (NaN, ±Infinity, or carrying a non-zero fractional part). -0 converts to 0.

    Decimal::to_decimal128_hex

    fn Decimal::to_decimal128_hex(self : Decimal, rounding? : Rounding) -> (String, Flags)

    Encode self as a decimal128 DPD interchange payload.

    Decimal::to_decimal32_hex

    fn Decimal::to_decimal32_hex(self : Decimal, rounding? : Rounding) -> (String, Flags)

    Encode self as a decimal32 DPD interchange payload in network-byte-order hexadecimal. The value is first rounded/clamped to the decimal32 format using rounding (default: half-even); any conditions raised by that format conversion are returned with the hex string.

    Decimal::to_decimal64_hex

    fn Decimal::to_decimal64_hex(self : Decimal, rounding? : Rounding) -> (String, Flags)

    Encode self as a decimal64 DPD interchange payload.

    Decimal::to_double

    fn Decimal::to_double(self : Decimal) -> Double

    Convert self to the nearest binary64 Double. Total but lossy: finite values round to nearest (delegating to the standard library's correctly-rounded decimal-string parser), magnitudes beyond binary64's range saturate to ±Infinity, and the decimal specials map across directly.

    Decimal::to_eng_string

    fn Decimal::to_eng_string(self : Decimal) -> String

    Convert a Decimal to its GDA to-engineering-string form: identical to to_sci_string except that, when exponential notation is used, the printed exponent is always a multiple of three and the integer part carries one to three digits (e.g. 7E-7 renders 700E-9).

    Decimal::to_int

    fn Decimal::to_int(self : Decimal) -> Int?

    The exact value of self as a machine Int, or None when it is not a finite integer or falls outside [Int::min_value, Int::max_value].

    Decimal::to_int64

    fn Decimal::to_int64(self : Decimal) -> Int64?

    The exact value of self as a machine Int64, or None when it is not a finite integer or falls outside [Int64::min_value, Int64::max_value].

    Decimal::to_integral_exact

    fn Decimal::to_integral_exact(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA to-integral-exact: round to integer, raising Inexact / Rounded exactly when the rounding discarded digits or changed the value. Behaviour-identical to quantize(self, 1, ctx) but with the Invalid_operation guard suppressed for "value too big to fit" — the op's purpose is to drop fractional digits, so it always succeeds for representable inputs.

    Decimal::to_integral_value

    fn Decimal::to_integral_value(self : Decimal, ctx : Context) -> (Decimal, Flags)

    GDA to-integral-value: round self to an integer (exponent 0) using the context's rounding mode, without raising Inexact or Rounded.

    IEEE-754 §5.9: the inexact result is intentional behaviour, so the operation suppresses those signals even when rounding actually happens. Implementations of currency / scoring scales reach for this when they want to drop fractional digits silently.

    Decimal::to_integral_exact is the same op but with normal flag raising.

    Decimal::to_json

    fn Decimal::to_json(self : Decimal) -> Json

    Decimal::to_sci_string

    fn Decimal::to_sci_string(self : Decimal) -> String

    Convert a Decimal to its GDA canonical to-scientific-string form.

    Algorithm follows §10.3 of the General Decimal Arithmetic specification:

    • Infinities render as Infinity (with sign).
    • NaNs render as NaN[payload] or sNaN[payload] (with sign).
    • Finite numbers render in plain notation when exponent <= 0 and the adjusted exponent exponent + (digit_count - 1) is >= -6, otherwise in scientific notation d.dddE+nnn / d.dddE-nnn with a mandatory sign on the exponent.

    Decimal::to_string

    fn Decimal::to_string(self : Decimal) -> String

    Decimal::try_finite

    fn Decimal::try_finite(coefficient :
    BigInt
    , exponent : Int, negative? : Bool) -> Decimal?

    Construct a finite decimal (-1)^negative * coefficient * 10^exponent, or None if coefficient is negative (the representation keeps the sign in negative and the coefficient non-negative). For a signed integer use from_bigint / from_int; this constructor is for when you need an explicit exponent (e.g. try_finite(150N, -2) is 1.50) or an explicit -0.

    Decimal::unsafe_finite

    fn Decimal::unsafe_finite(coefficient :
    BigInt
    , exponent : Int, negative? : Bool) -> Decimal

    Low-level finite constructor that trusts coefficient >= 0 and skips the check. The result is malformed (and downstream behavior undefined) if the coefficient is negative — callers maintaining the representation invariant use this; everyone else uses try_finite or from_bigint.

    Decimal::zero

    fn Decimal::zero() -> Decimal

    The decimal +0.

    Flags

    pub(all) struct Flags {
    inexact : Bool
    rounded : Bool
    invalid_operation : Bool
    division_by_zero : Bool
    overflow : Bool
    underflow : Bool
    subnormal : Bool
    clamped : Bool
    conversion_syntax : Bool
    division_impossible : Bool
    division_undefined : Bool
    insufficient_storage : Bool
    invalid_context : Bool
    } derive(Eq)

    GDA status flags accumulated by Context-aware ops. All flags are set additively (never cleared by an op); a sequence of ops reports whether any of them triggered the signal.

    Flags::combine

    fn Flags::combine(self : Flags, other : Flags) -> Flags

    Combine two flag sets — the union of every raised signal.

    Flags::equal

    fn Flags::equal(Flags, Flags) -> Bool

    Flags::new

    fn Flags::new() -> Flags

    A fresh Flags with every signal cleared.

    Flags::not_equal

    fn Flags::not_equal(x : Flags, y : Flags) -> Bool

    Rounding

    pub(all) enum Rounding {
    HalfUp
    HalfEven
    HalfDown
    Up
    Down
    Ceiling
    Floor
    ZeroFiveUp
    } derive(Eq)

    GDA rounding modes for finite-result finalisation.
    impl Show for Rounding

    Rounding::equal

    fn Rounding::equal(Rounding, Rounding) -> Bool

    Rounding::not_equal

    fn Rounding::not_equal(x : Rounding, y : Rounding) -> Bool

    Rounding::output

    fn Rounding::output(self : Rounding, logger : &Logger) -> Unit

    Rounding::to_string

    fn Rounding::to_string(self : Rounding) -> String

    default_context

    fn default_context() -> Context

    The baseline context for the arithmetic operators when no with_context block is active: a fresh decimal128 (precision 34, half-even). Override it for a dynamic extent with with_context.

    with_context

    fn[T] with_context(ctx : Context, f : () -> T) -> (T, Flags)

    Run f with the arithmetic operators (+ - * /, unary -) evaluating under ctx for the dynamic extent of the call, then restore the previously active context. Returns f's result together with the status flags every operator inside the block accumulated.

    The caller's own ctx value is never mutated: the block runs on a fresh copy with cleared flags. Blocks nest — an inner with_context restores the outer context on exit, not the global default.

    let (sum, _flags) = with_context(Context::decimal64(), fn() { Decimal::from_int(1) + Decimal::from_int(2) // evaluated at 16-digit decimal64 })