Arbitrary-precision decimal arithmetic for MoonBit
moon add moonbit-community/decimalimport {
"moonbit-community/decimal",
}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# 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
moon bench -p moonbit-community/decimal/tests/benchmarksnix develop # or: direnv allow
moon check| Path | Contents |
|---|---|
| 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 |
pub(all) suberror ParseError {
Empty
ExpectedDigit(position~ : Int)
InvalidExponent(position~ : Int)
TrailingGarbage(position~ : Int)
BadKeyword(position~ : Int)
} derive(Eq)impl Show for ParseError -NaN(p) ... < -sNaN(p) ... < -Infinity < -finite ... <
+0 = -0 (per numerical value, broken by exponent)
... +finite < +Infinity < +sNaN(p) ... < +NaN(p) ...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]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)let (sum, _flags) = with_context(Context::decimal64(), fn() {
Decimal::from_int(1) + Decimal::from_int(2) // evaluated at 16-digit decimal64
})