Lightweight, precise monetary calculation utilities using decimal.js
npm install @themainstack/money-utilsLightweight and precision-safe monetary math utilities built on decimal.js. Provides deterministic arithmetic, rounding, percentage helpers, conversions, and aggregate helpers.
See src/ for implementation and tests/ for example usages.
``bash
yarn add @themainstack/money-utilsor, if testing locally
yarn link
`
`ts
// Preferred: named imports for tree-shaking
import MoneyMath, {
add,
percentOf,
sum,
distribute,
toMinor,
toMajor,
} from '@themainstack/money-utils';
// arithmetic (named import)
const total = add(1.23, 2.45); // 3.68
// percent (named import)
const p = percentOf(200, 10); // 20
// sum (named import)
const s = sum([1.23, 2.34, 3.33]); // 6.9
// distribute (preserves minor units)
const parts = distribute(100, 3, 'USD'); // [33.34, 33.33, 33.33]
// conversions
const cents = toMinor(1.23, 'USD'); // 123
const major = toMajor(123, 'USD'); // 1.23
// Or use the default MoneyMath object (convenience)
const total2 = MoneyMath.add(1.23, 2.45);
``
- add(a, b, options?) => number | string | Decimal
- a, b: number|string|Decimal
- options: { precision?: number; rounding?: RoundingMode; returnString?: boolean; returnDecimal?: boolean }
- subtract(a, b, options?) => number | string | Decimal
- multiply(a, b, options?) => number | string | Decimal
- divide(a, b, options?) => number | string | Decimal
- round(value, precision?, options?) => number | string | Decimal
- toMinor(value, currencyOrDecimals?, options?) => number | string | Decimal
- toMajor(minor, currencyOrDecimals?, options?) => number | string | Decimal
- percentOf(base, percent, options?) => number | string | Decimal
- sum(values[], options?) => number | string | Decimal
- average(values[], options?) => number | string | Decimal
- distribute(amount, parts, currencyOrDecimals?, options?) => Array