@themainstack/money-utils
v1.3.1
Published
Lightweight, precise monetary calculation utilities using decimal.js
Maintainers
Readme
@themainstack/money-utils
Lightweight 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.
Installation
yarn add @themainstack/money-utils
# or, if testing locally
yarn link
Usage examples
// 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);API Reference
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<number|string|Decimal>
