Skip to content

atom ​

@c9up/atom: exact decimal arithmetic, statistics and currency-bound money values, on a Rust engine with a TypeScript fallback. Guide: Decimals and money.

Installation ​

bash
pnpm add @c9up/atom

The Rust engine loads through N-API in Node, WebAssembly in the browser and a JSI module on a phone (declared in reamNative, linked by ream android:*). Where none loads, the TypeScript engine answers with the same digits.

In Node, the binary comes in one npm package per platform, which @c9up/atom lists as an optional dependency at its exact version: @c9up/atom-linux-x64-gnu, @c9up/atom-linux-arm64-gnu, @c9up/atom-darwin-x64, @c9up/atom-darwin-arm64, @c9up/atom-win32-x64-msvc. The package manager installs only the one that matches the machine. An install that omits optional dependencies (--no-optional, --omit=optional) skips it: atom then runs on the TypeScript engine, and nativeAtom() throws E_ATOM_ENGINE_NOT_FOUND, naming the package to install, with the load error as its cause. The WebAssembly engine and the sources of the phone build are the same on every platform: they stay in @c9up/atom.

Entry points ​

ImportContents
@c9up/atomDecimal, Money, the aggregates, the Atom namespace, the context functions and Atom.bulk plans.
@c9up/atom/atlasThe column adapters for @c9up/atlas: decimalColumn and decimalAtlasAdapter.

Exports ​

@c9up/atom ​

ExportKindDescription
DecimalclassAn exact decimal value. Immutable: every operation returns a new one.
decimalfunctiondecimal(value: DecimalInput): Decimal, the same as Decimal.from.
MoneyclassAn amount bound to a currency and held at that currency's scale.
moneyfunctionmoney(amount: DecimalInput, currency: string, options?: MoneyOptions): Money.
errorsnamespaceThe package's errors, one class per code, see Errors
sumfunctionExact sum. An empty input is 0.
avgfunctionArithmetic mean. Throws on an empty input.
medianfunctionMiddle value; the mean of the two middle values for an even count.
modefunctionThe values that appear most often, sorted. [] when no value repeats.
stddevfunctionStandard deviation, population by default.
minfunctionSmallest value. Throws on an empty input.
maxfunctionLargest value. Throws on an empty input.
AtomconstNamespace: decimal, bulk, sum, avg, median, mode, stddev, min, max, parseLocale, money.
bulkfunctionPlans a computation over columns and runs it in one call into the engine.
BulkclassA plan: the b a bulk callback receives.
BulkColumnclassA planned column of values.
BulkScalarclassA planned single value.
configureAtomContextfunctionChanges the default precision and rounding modes.
getAtomContextfunctionA copy of the context in force.
resetAtomContextfunctionRestores the defaults.
withAtomContextfunctionRuns a callback under other defaults.
isNativeAvailablefunctionisNativeAvailable(): boolean: whether the Rust engine (N-API or WASM) loaded.
DecimalInputtypestring | number | bigint | Decimal.
RoundModetype'trunc' | 'floor' | 'ceil' | 'half-up' | 'half-even'.
DecimalScaledinterface{ value: bigint; scale: number }, as toParts() returns it.
DecimalSafeParseResulttype{ success: true; value: Decimal } | { success: false; error: Error }.
DivOptions, PowOptions, SqrtOptionsinterface{ precision?: number; mode?: RoundMode }.
MedianOptionsinterface{ precision?: number; mode?: RoundMode }.
StddevOptionsinterface{ sample?: boolean; precision?: number; mode?: RoundMode }.
QuantizeOptionsinterface{ mode?: RoundMode }.
BetweenOptionsinterface{ inclusive?: boolean }, true by default.
ToMinorUnitsOptionsinterface{ exact?: boolean; mode?: RoundMode }.
MoneyOptionsinterface{ scale?: number; exact?: boolean; mode?: RoundMode }.
MoneyRoundingOptionsinterface{ mode?: RoundMode }.
MoneyFormatOptionsinterfaceIntl.NumberFormatOptions without style and currency, plus locale?: Intl.LocalesArgument.
AtomContextinterface{ precision: number; roundMode: RoundMode; quantizeMode: RoundMode; maxDigits: number; maxExponent: number; maxScale: number }.
AtomContextOptionstypePartial<AtomContext>.
BulkDivOptionsinterface{ precision?: number; mode?: RoundMode }.
BulkStddevOptionsinterfaceBulkDivOptions plus sample?: boolean.

Pass strings or bigints for business data: a number that is not a safe integer is refused.

Aggregates ​

Each aggregate takes either one iterable or the values as arguments.

FunctionSignatureDescription
sumsum(...args: [Iterable<DecimalInput>] | DecimalInput[]): DecimalExact sum, through the engine's batch entry.
avgavg(...args: [Iterable<DecimalInput>] | DecimalInput[]): DecimalSum divided by the count, at the context precision.
medianmedian(...args: [Iterable<DecimalInput>, MedianOptions?] | DecimalInput[]): DecimalOptions apply only with the iterable form.
modemode(...args: [Iterable<DecimalInput>] | DecimalInput[]): Decimal[]Every most frequent value.
stddevstddev(...args: [Iterable<DecimalInput>, StddevOptions?] | DecimalInput[]): Decimalsample: true divides by N-1 and needs two values. The mean and the variance carry eight digits more than precision.
min / maxmin(...args: [Iterable<DecimalInput>] | DecimalInput[]): Decimal

Decimal ​

MemberSignatureDescription
constructornew Decimal(value: DecimalInput, scaleHint?: number)Parses the value. scaleHint is the scale toParts() reports.
from / parsestatic from(value: DecimalInput): DecimalSame as the constructor.
tryParsestatic tryParse(value: unknown): Decimal | nullnull instead of throwing.
safeParsestatic safeParse(value: unknown): DecimalSafeParseResultA result object instead of throwing.
isDecimalstatic isDecimal(value: unknown): value is Decimal
sumstatic sum(values: Iterable<DecimalInput>): DecimalThe whole batch in one call into the engine; equal to folding plus.
dotstatic dot(a: Iterable<DecimalInput>, b: Iterable<DecimalInput>): DecimalΣ aᵢ·bᵢ in one call. Throws when the lengths differ.
zero / onestatic zero(): Decimal
fromMinorUnitsstatic fromMinorUnits(value: string | number | bigint, scale: number): DecimalfromMinorUnits(1999n, 2) is 19.99.
parseLocalestatic parseLocale(value: string, localesOrRosetta?: Intl.LocalesArgument | RosettaLike): DecimalParses '1.234,56' in the locale's separators. A rosetta instance can stand for the locale.
plus / minus / timesplus(other: DecimalInput): DecimalExact.
divdiv(other: DecimalInput, options?: DivOptions): DecimalRounded once, from the exact quotient, to precision digits in mode.
modmod(other: DecimalInput): Decimal
powpow(exp: number, options?: PowOptions): DecimalInteger exponent up to MAX_EXPONENT_ABS (100 000) either sign; a negative one divides.
sqrtsqrt(options?: SqrtOptions): Decimal
cmpcmp(other: DecimalInput): -1 | 0 | 1
eq / lt / lte / gt / gteeq(other: DecimalInput): boolean
min / maxmin(other: DecimalInput): Decimal
clampclamp(min: DecimalInput, max: DecimalInput): DecimalThrows when min > max.
betweenbetween(min: DecimalInput, max: DecimalInput, options?: BetweenOptions): booleanInclusive by default.
abs / negabs(): Decimal
isZero / isPositive / isNegative / isIntegerisZero(): booleanisPositive() is false for zero.
trunc / floor / ceiltrunc(scale = 0): DecimalRounds to scale digits in that mode.
round / toScaletoScale(scale = 0, mode?: RoundMode): DecimalRounds to scale digits, in the context's roundMode by default.
quantizequantize(step: DecimalInput, options?: QuantizeOptions): DecimalNearest multiple of step ('0.05'), in the context's quantizeMode by default.
toFixedtoFixed(scale: number, mode?: RoundMode): stringExactly scale fractional digits.
toMinorUnitstoMinorUnits(scale: number, options?: ToMinorUnitsOptions): bigintThrows on a loss of digits unless exact: false, which rounds in mode ('trunc' by default).
percentpercent(rate: DecimalInput, options?: DivOptions): Decimalthis × rate / 100.
applyPercentapplyPercent(rate: DecimalInput, options?: DivOptions): Decimalthis + this × rate / 100.
percentageOfpercentageOf(total: DecimalInput, options?: DivOptions): Decimalthis / total × 100.
allocateallocate(ratios: Array<string | number | bigint>): Decimal[]Splits by integer ratios; the shares add up to the value exactly, the remainder going to the largest remainders first.
toPartstoParts(): DecimalScaledInteger value and scale.
toString / toJSONtoString(): stringCanonical form, trailing zeros trimmed ('1.2300' prints '1.23').
toNumbertoNumber(): numberLossy past 15 to 16 significant digits.
toLocaletoLocale(localesOrRosetta?: Intl.LocalesArgument | RosettaLike, options?: Intl.NumberFormatOptions): stringExact localized formatting.

The scale of a value is not kept through arithmetic: to store or to allocate, pass the scale your column declares (toFixed(2), toScale(2)).

Money ​

The scale comes from ISO 4217 (JPY and ISK 0, JOD and KWD 3, 2 for any currency not listed); scale overrides it. Operations across two currencies, or two scales, throw.

MemberSignatureDescription
constructornew Money(amount: DecimalInput, currency: string, options?: MoneyOptions)currency is a three-letter code. With exact (the default), an amount with more digits than the scale throws; exact: false rounds in mode.
fromMajorstatic fromMajor(amount: DecimalInput, currency: string, options?: MoneyOptions): MoneySame as the constructor.
fromMinorUnitsstatic fromMinorUnits(minorUnits: string | number | bigint, currency: string, options?: Omit<MoneyOptions, 'exact'>): MoneyfromMinorUnits(1999n, 'EUR') is 19.99 EUR.
amountget amount(): Decimal
currencyget currency(): stringUpper-case code.
scaleget scale(): number
plus / minusplus(other: Money): Money
timestimes(multiplier: DecimalInput, options?: MoneyRoundingOptions): MoneyRounded to the currency's scale.
divdiv(divisor: DecimalInput, options?: MoneyRoundingOptions): MoneyRounded once to the currency's scale.
allocateallocate(ratios: Array<string | number | bigint>): Money[]No cent lost: 10.00 by [1, 1, 1] is 3.34, 3.33, 3.33.
toMinorUnitstoMinorUnits(): bigintThe integer to store.
formatformat(options?: MoneyFormatOptions): stringIntl currency formatting at the currency's scale.
toStringtoString(): string'19.99 EUR'.
toJSONtoJSON(): { amount: string; currency: string }

bulk ​

ts
function bulk<T extends Readonly<Record<string, BulkScalar>>>(build: (b: Bulk) => T): { [K in keyof T]: Decimal }
function bulk(): Bulk

The callback form plans and runs once. Without a callback, it returns the plan, to run more than once. Planned values refuse toString(), valueOf() and toJSON() until the plan has run. The plan runs on the Rust engine within a 128-bit width and re-runs on the BigInt executor when a value is wider.

Bulk memberSignatureDescription
columncolumn(values: Iterable<DecimalInput>): BulkColumnEvery column of one plan has the same length. A plan runs only the columns it loaded.
minorUnitsminorUnits(values: Iterable<string | number | bigint>, scale: number): BulkColumnA column held as minor units; the fastest way in.
ofof(value: DecimalInput): BulkScalarA single value.
runrun<T>(outputs: T): { [K in keyof T]: Decimal }Computes the named outputs.
runAsyncrunAsync<T>(outputs: T): Promise<{ [K in keyof T]: Decimal }>Off the JS thread where the engine can (the JSI module on a phone); otherwise run.
BulkColumn memberDescription
plus, minus, timesElement-wise, with a column or a scalar.
neg, abs, sortedA new column.
sum, min, maxA scalar.
dot(other: BulkColumn)Σ aᵢ·bᵢ in one pass.
at(index: number)One element; throws outside the column.
avg(options?), median(options?)Take BulkDivOptions.
percentile(fraction: number)Nearest rank, fraction in [0, 1].
stddev(options?: BulkStddevOptions)Same definition as stddev.

BulkScalar has plus, minus, times, div(other, options?), neg, abs, min, max, pow(exp, options?) and sqrt(options?).

@c9up/atom/atlas ​

ExportKindDescription
decimalColumnfunctiondecimalColumn(options?: DecimalColumnOptions): DecimalAtlasColumn: the argument of @Column(...) for a decimal column.
decimalAtlasAdapterconst{ consume, prepare } without scale or nullability; frozen.
DecimalColumnOptionsinterfaceSee below.
DecimalAtlasAdapterinterface{ consume(raw: unknown): Decimal | null; prepare(value: unknown): string | null }.
DecimalAtlasColumninterfaceDecimalAtlasAdapter plus type: 'decimal' | 'numeric' and nullable: boolean.

prepare refuses anything that is not a Decimal, so a plain number never reaches the column. Configure the database driver to return decimal columns as strings: a value that arrives as a JS number has lost its digits already.

DecimalColumnOptionsTypeDefaultDescription
scalenumbernoneScale the value is held at, read and written.
exactbooleantrueThrow on a value with more digits than scale; false rounds.
modeRoundMode'half-up'Rounding when exact is false.
nullablebooleantruefalse throws on a null either way.
columnType'decimal' | 'numeric''decimal'The column type the binds cast to.

Configuration ​

The context sets the defaults of div, pow, sqrt, quantize and the aggregates. configureAtomContext changes them for the process, or for the current withAtomContext scope only; on Node an async callback keeps its scope across await.

ts
configureAtomContext(options: AtomContextOptions): AtomContext
withAtomContext<T>(options: AtomContextOptions, callback: () => T): T
getAtomContext(): AtomContext
resetAtomContext(): AtomContext
OptionTypeDefaultDescription
precisionnumber18Fractional digits of a quotient, a root or a negative power.
roundModeRoundMode'half-up'Rounding of those results and of toScale, toFixed.
quantizeModeRoundMode'half-up'Rounding of quantize and of Money.
maxDigitsnumber20000Most significant digits an input may carry; longer input is refused (ceiling 1 000 000).
maxExponentnumber100How far the exponent of a scientific literal (1e-18, 2.5E+6) or of a number may move the decimal point, either way; a wider one is refused before it is written out (ceiling 10 000).
maxScalenumber10000Most fractional digits a value, a precision or a scale may carry (ceiling 10 000). It may not be lower than precision.

1e-9990 is seven bytes and a value of ten thousand digits: every operation that reads it pays for them. maxExponent refuses such a literal when it is read. Raise it only where you need such values. A list of amounts taken from a request costs work for each of its values, so bound its length in the application too.

Errors ​

CodeRaised when
E_ATOM_INVALID_INPUTA value given as a decimal is not a string, number, bigint or Decimal
E_ATOM_INVALID_DECIMALA string or number does not read as a decimal (parseLocale included)
E_ATOM_UNSAFE_INTEGERA JavaScript number is an integer past Number.MAX_SAFE_INTEGER; pass a string or a bigint
E_ATOM_INVALID_INTEGERMinor units are not a whole number
E_ATOM_DECIMAL_TOO_LARGEA value or a result is past the maxDigits significant-digit bound, or a literal's exponent is past maxExponent
E_ATOM_INVALID_SCALEA scale or a precision is not a whole number from 0 to maxScale (10 000 by default)
E_ATOM_INVALID_EXPONENTA pow exponent is not a whole number in range
E_ATOM_INVALID_ROUNDING_MODEA rounding mode is not one atom knows
E_ATOM_INVALID_RANGEclamp / between got a minimum greater than the maximum
E_ATOM_INVALID_STEPA quantize step is not greater than zero
E_ATOM_INVALID_RATIOSallocate got no ratio, a negative one, or none positive
E_ATOM_PRECISION_LOSStoMinorUnits (and an exact Money) would lose digits at that scale
E_ATOM_LENGTH_MISMATCHDecimal.dot got two lists of different lengths
E_ATOM_DIVISION_BY_ZEROA division or a modulo by zero
E_ATOM_NEGATIVE_SQRTsqrt of a negative value
E_ATOM_EMPTY_INPUTavg, min, max, median or stddev got no value
E_ATOM_TOO_FEW_VALUESA sample stddev got fewer than two values
E_ATOM_INVALID_CONTEXTconfigureAtomContext / withAtomContext got a setting that is not valid
E_ATOM_INVALID_CURRENCYA currency code is not three letters
E_ATOM_CURRENCY_MISMATCHTwo Money values of different currencies or scales were combined
E_ATOM_INVALID_COLUMN_VALUEThe Atlas adapter got a column value of the wrong type
E_ATOM_NULL_COLUMN_VALUEA non-nullable decimalColumn got null
E_ATOM_ENGINE_NOT_FOUNDnativeAtom() found no native engine (N-API, WASM or the phone's JSI module)
E_ATOM_NAPI_DISABLEDnativeAtom() ran while a test disabled the native engine
E_ATOM_INTERNALAn internal invariant broke, or the native engine panicked (a bug in atom)
E_ATOM_BULK_NOT_RUNA planned value was read before run()
E_ATOM_BULK_NO_OUTPUTrun() got no value to compute
E_ATOM_BULK_BAD_OUTPUTrun() got something that is not a planned value
E_ATOM_BULK_LENGTH_MISMATCHA plan's columns have different lengths
E_ATOM_BULK_FOREIGN_COLUMNrun() / runAsync() got a value that reads a column of another plan
E_ATOM_BULK_EMPTY_COLUMNA column has no value
E_ATOM_BULK_BAD_INDEXat() is outside the column
E_ATOM_BULK_BAD_PERCENTILEA percentile is not a fraction between 0 and 1
E_ATOM_BULK_BAD_EXPONENTA planned pow exponent is not a whole number in range
E_ATOM_BULK_BAD_PRECISIONA planned precision is not a whole number from 0 to maxScale (10 000 by default)
E_ATOM_BULK_BAD_SCALEminorUnits() got a scale that is not one
E_ATOM_BULK_NOT_MINOR_UNITSminorUnits() got a value that is not a whole number of minor units
E_ATOM_BULK_TOO_SHORTA planned sample standard deviation has fewer than two values
E_ATOM_BULK_NO_LENGTHA column was built with no source (a bug in atom)
E_ATOM_BULK_BAD_PROGRAMThe TypeScript evaluator or the native engine met a malformed plan (a bug in atom)
E_ATOM_BULK_LOST_OUTPUTA run returned fewer values than it was asked for (a bug in atom)

Each one is a class of the errors namespace and a @c9up/flare Exception with status 500: branch on error.code or on error instanceof errors.E_ATOM_*. The Rust engine and the TypeScript engine raise the same errors; a refusal of the Rust engine keeps its original error as cause. The engine names the refusal by its code, at the start of that error's message (E_ATOM_DIVISION_BY_ZERO: Division by zero), and atom raises the class of that code.

Migration ​

  • AtomError is gone: test error.code, or error instanceof errors.E_ATOM_* with import { errors } from '@c9up/atom'.
  • AtomTypeError is gone, and the Atlas adapter's refusals are no longer a TypeError: replace instanceof TypeError with error.code === 'E_ATOM_INVALID_COLUMN_VALUE' (or E_ATOM_NULL_COLUMN_VALUE).
  • A refusal of the Rust engine (division by zero, negative root...) now carries its E_ATOM_* code instead of none: code that matched its message can test the code.
  • A scientific literal or a number whose exponent is past ±100 ('1e-101', 1e-150) is now refused with E_ATOM_DECIMAL_TOO_LARGE; an exponent past ±10 000 was refused with E_ATOM_INVALID_DECIMAL and now raises E_ATOM_DECIMAL_TOO_LARGE too. If you read wider values, raise the bound: configureAtomContext({ maxExponent: 10_000 }).
  • run() and runAsync() now refuse a planned value that reads a column loaded on another Bulk, with E_ATOM_BULK_FOREIGN_COLUMN, even when the lengths match. Load every column on the plan that runs it.

See also ​