@jdsalasc/solvejs-money 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +125 -3
- package/dist/cjs/index.cjs +361 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/esm/index.d.ts +168 -0
- package/dist/esm/index.js +347 -0
- package/dist/esm/index.js.map +1 -0
- package/package.json +68 -6
package/README.md
CHANGED
|
@@ -1,3 +1,125 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @jdsalasc/solvejs-money
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@jdsalasc/solvejs-money)
|
|
4
|
+
[](https://www.npmjs.com/package/@jdsalasc/solvejs-money)
|
|
5
|
+
|
|
6
|
+
Zero-dependency money math in integer minor units: exact addition, percentages, allocation without lost cents, and currency-aware formatting. No floating-point rounding surprises in invoices, payments, or tax calculations.
|
|
7
|
+
|
|
8
|
+
## Utilities
|
|
9
|
+
|
|
10
|
+
- `fromDecimal`
|
|
11
|
+
- `toDecimal`
|
|
12
|
+
- `addMoney`
|
|
13
|
+
- `subtractMoney`
|
|
14
|
+
- `sumMoney`
|
|
15
|
+
- `multiplyMoney`
|
|
16
|
+
- `percentageOf`
|
|
17
|
+
- `applyPercentage`
|
|
18
|
+
- `allocateAmount`
|
|
19
|
+
- `formatMoney`
|
|
20
|
+
- `MoneyError`
|
|
21
|
+
|
|
22
|
+
## When to use this package
|
|
23
|
+
|
|
24
|
+
Use it for anything that adds up and has to reconcile: invoices, order totals, split payments,
|
|
25
|
+
percentage discounts, tax. Money in a float loses cents silently, and the loss shows up as a
|
|
26
|
+
dispute rather than a bug report.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npm i @jdsalasc/solvejs-money
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Why integer minor units
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
0.1 + 0.2 === 0.30000000000000004; // the float problem
|
|
38
|
+
|
|
39
|
+
fromDecimal("0.1") + fromDecimal("0.2"); // 30, exactly
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Every function here takes and returns an integer count of minor units: cents for USD, yen for JPY,
|
|
43
|
+
nothing at all for a zero-decimal currency.
|
|
44
|
+
|
|
45
|
+
## Quick example
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { fromDecimal, toDecimal, multiplyMoney, applyPercentage, allocateAmount, formatMoney } from "@jdsalasc/solvejs-money";
|
|
49
|
+
|
|
50
|
+
const unit = fromDecimal("19.99"); // 1999
|
|
51
|
+
const subtotal = multiplyMoney(unit, 3); // 5997
|
|
52
|
+
const discounted = applyPercentage(subtotal, -10); // 5397, a 10% discount
|
|
53
|
+
const taxed = applyPercentage(discounted, 21); // 6530
|
|
54
|
+
|
|
55
|
+
toDecimal(taxed); // "65.30"
|
|
56
|
+
formatMoney(taxed); // "$65.30"
|
|
57
|
+
|
|
58
|
+
allocateAmount(taxed, [1, 1, 1]); // [2180, 2175, 2175], sums back exactly
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Compare with the float path: `((19.99 * 3) * 0.9 * 1.21).toFixed(2)` is `"65.31"`, one cent off.
|
|
62
|
+
|
|
63
|
+
## Allocation never loses a unit
|
|
64
|
+
|
|
65
|
+
`allocateAmount` uses the largest-remainder method, so the parts always sum back to the total. The
|
|
66
|
+
leftover units go to the largest fractional shares first, earliest part winning a tie, which makes
|
|
67
|
+
the result deterministic:
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
allocateAmount(1000, [1, 1, 1]); // [334, 333, 333]
|
|
71
|
+
allocateAmount(100, [3, 1]); // [75, 25]
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Rounding is explicit
|
|
75
|
+
|
|
76
|
+
Any fractional result is settled by a mode you choose. The default is `half-away-from-zero`, which is
|
|
77
|
+
what invoices and tax tables expect.
|
|
78
|
+
|
|
79
|
+
| Mode | `52.5` becomes | `-52.5` becomes |
|
|
80
|
+
|---|---:|---:|
|
|
81
|
+
| `half-away-from-zero` (default) | 53 | -53 |
|
|
82
|
+
| `half-up` | 53 | -52 |
|
|
83
|
+
| `floor` | 52 | -53 |
|
|
84
|
+
| `ceil` | 53 | -52 |
|
|
85
|
+
| `down` | 52 | -52 |
|
|
86
|
+
|
|
87
|
+
`floor` and `ceil` follow the maths definitions, so they are asymmetric on negatives. Use `down` when
|
|
88
|
+
you want truncation toward zero.
|
|
89
|
+
|
|
90
|
+
## Limitations and Constraints
|
|
91
|
+
|
|
92
|
+
### Input precision is refused, not rounded
|
|
93
|
+
|
|
94
|
+
`fromDecimal` converts exactly or throws. `"2.675"` for a two-digit currency is an error, not `268`:
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
fromDecimal("2.675"); // throws
|
|
98
|
+
fromDecimal("1.5000"); // 150, trailing zeros are not precision
|
|
99
|
+
fromDecimal("0.006", { fractionDigits: 3 }); // 6
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Silently rounding an input amount is how an invoice dispute starts. Round deliberately, at a step you
|
|
103
|
+
choose, with `multiplyMoney` and its `rounding` option.
|
|
104
|
+
|
|
105
|
+
### Minor units are safe integers only
|
|
106
|
+
|
|
107
|
+
`Number.MAX_SAFE_INTEGER` is the ceiling, which is about 90 trillion USD. Beyond that, use a bigint
|
|
108
|
+
pipeline or a database decimal type.
|
|
109
|
+
|
|
110
|
+
### formatMoney asks Intl for the fraction digits
|
|
111
|
+
|
|
112
|
+
A currency's own digits decide the rendering, so JPY shows no fraction and BHD shows three. It passes
|
|
113
|
+
the amount through `Number`, so it is a display helper only. Never parse the output back into an
|
|
114
|
+
amount.
|
|
115
|
+
|
|
116
|
+
### A malformed locale or currency throws
|
|
117
|
+
|
|
118
|
+
`formatMoney(1234, { locale: "not a locale" })` throws a `RangeError` from `Intl`. That is a
|
|
119
|
+
configuration mistake, and guessing a locale would hide it. `MoneyError` covers the amount arguments,
|
|
120
|
+
`RangeError` covers the locale and currency.
|
|
121
|
+
|
|
122
|
+
### Weights must be non-negative whole numbers
|
|
123
|
+
|
|
124
|
+
`allocateAmount` refuses negative, fractional and all-zero weights, because there is no sensible way
|
|
125
|
+
to split an amount among them. Pass a percentage as an integer like `20` for twenty percent.
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MoneyError = void 0;
|
|
4
|
+
exports.fromDecimal = fromDecimal;
|
|
5
|
+
exports.toDecimal = toDecimal;
|
|
6
|
+
exports.addMoney = addMoney;
|
|
7
|
+
exports.subtractMoney = subtractMoney;
|
|
8
|
+
exports.sumMoney = sumMoney;
|
|
9
|
+
exports.multiplyMoney = multiplyMoney;
|
|
10
|
+
exports.percentageOf = percentageOf;
|
|
11
|
+
exports.applyPercentage = applyPercentage;
|
|
12
|
+
exports.allocateAmount = allocateAmount;
|
|
13
|
+
exports.formatMoney = formatMoney;
|
|
14
|
+
/**
|
|
15
|
+
* Error thrown by the money utilities.
|
|
16
|
+
*
|
|
17
|
+
* Carries a stable machine-readable `code` and a `details` context object.
|
|
18
|
+
*/
|
|
19
|
+
class MoneyError extends Error {
|
|
20
|
+
constructor(code, message, details = {}) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.name = "MoneyError";
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.details = details;
|
|
25
|
+
Object.setPrototypeOf(this, MoneyError.prototype);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
exports.MoneyError = MoneyError;
|
|
29
|
+
function fail(code, message, details = {}) {
|
|
30
|
+
throw new MoneyError(code, message, details);
|
|
31
|
+
}
|
|
32
|
+
const ROUNDING_MODES = ["half-away-from-zero", "half-up", "floor", "ceil", "down"];
|
|
33
|
+
// A plain decimal string. Deliberately narrow: no exponent, no currency symbol, no separators.
|
|
34
|
+
// eslint-disable-next-line security/detect-unsafe-regex -- anchored, no nested quantifier
|
|
35
|
+
const DECIMAL = /^(-?)(\d+)(?:\.(\d+))?$/;
|
|
36
|
+
function assertFractionDigits(value) {
|
|
37
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
38
|
+
fail("MONEY_INVALID_FRACTION_DIGITS", "Expected fractionDigits to be a non-negative integer.", {
|
|
39
|
+
received: value
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function assertMinorUnits(value, label = "minor units") {
|
|
44
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) {
|
|
45
|
+
fail("MONEY_INVALID_MINOR_UNITS", `Expected ${label} to be a safe integer.`, { received: value });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function assertFactor(value, label = "factor") {
|
|
49
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
50
|
+
fail("MONEY_INVALID_FACTOR", `Expected ${label} to be a finite number.`, { received: value });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function round(value, mode) {
|
|
54
|
+
switch (mode) {
|
|
55
|
+
case "floor":
|
|
56
|
+
return Math.floor(value);
|
|
57
|
+
case "ceil":
|
|
58
|
+
return Math.ceil(value);
|
|
59
|
+
case "down":
|
|
60
|
+
// Toward zero, unlike floor on a negative result.
|
|
61
|
+
return value < 0 ? Math.ceil(value) : Math.floor(value);
|
|
62
|
+
case "half-up":
|
|
63
|
+
// Ties go toward positive infinity, so -0.5 settles to 0.
|
|
64
|
+
return Math.round(value);
|
|
65
|
+
default:
|
|
66
|
+
// Half away from zero, which is what invoices and tax tables expect.
|
|
67
|
+
return value < 0 ? -Math.round(-value) : Math.round(value);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function parseDecimal(raw, value) {
|
|
71
|
+
const match = raw.trim().match(DECIMAL);
|
|
72
|
+
if (!match) {
|
|
73
|
+
fail("MONEY_INVALID_DECIMAL", `Expected a plain decimal amount, received ${JSON.stringify(value)}.`, {
|
|
74
|
+
received: value
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const [, sign, whole, fraction = ""] = match;
|
|
78
|
+
return { sign, whole, fraction };
|
|
79
|
+
}
|
|
80
|
+
function assertExactPrecision(fraction, fractionDigits, value) {
|
|
81
|
+
// Conversion is exact or refused. Rounding an input amount silently is how an invoice dispute
|
|
82
|
+
// starts, so anything beyond the currency's own precision is an error rather than a rounded value.
|
|
83
|
+
if (/[^0]/.test(fraction.slice(fractionDigits))) {
|
|
84
|
+
fail("MONEY_INVALID_DECIMAL", `Expected at most ${fractionDigits} fraction digits.`, {
|
|
85
|
+
received: value,
|
|
86
|
+
fractionDigits
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function scaleDecimal(whole, fraction, fractionDigits, value) {
|
|
91
|
+
const kept = fraction.padEnd(fractionDigits, "0").slice(0, fractionDigits);
|
|
92
|
+
const scaled = Number(`${whole}${kept}`);
|
|
93
|
+
if (!Number.isSafeInteger(scaled)) {
|
|
94
|
+
fail("MONEY_INVALID_DECIMAL", "Expected an amount within the safe integer range.", { received: value });
|
|
95
|
+
}
|
|
96
|
+
return scaled;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Converts a decimal amount into integer minor units.
|
|
100
|
+
*
|
|
101
|
+
* Parsing the decimal as a string keeps the conversion exact: `"2.675"` becomes `268` minor units
|
|
102
|
+
* for a two-digit currency rather than inheriting the float `2.674999...`.
|
|
103
|
+
*
|
|
104
|
+
* @param value - Decimal amount as a string, or a number you already trust.
|
|
105
|
+
* @param options - Conversion options.
|
|
106
|
+
* @param options.fractionDigits - Digits the currency supports. Defaults to 2.
|
|
107
|
+
* @returns Amount in minor units.
|
|
108
|
+
* @throws {MoneyError} `MONEY_INVALID_DECIMAL` or `MONEY_INVALID_FRACTION_DIGITS`.
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* fromDecimal("19.99"); // 1999
|
|
112
|
+
* fromDecimal("0.07"); // 7
|
|
113
|
+
*/
|
|
114
|
+
function fromDecimal(value, options = {}) {
|
|
115
|
+
const fractionDigits = options.fractionDigits ?? 2;
|
|
116
|
+
assertFractionDigits(fractionDigits);
|
|
117
|
+
const raw = typeof value === "number" ? value.toString() : value;
|
|
118
|
+
if (typeof raw !== "string") {
|
|
119
|
+
fail("MONEY_INVALID_DECIMAL", "Expected a decimal string or a number.", { received: typeof value });
|
|
120
|
+
}
|
|
121
|
+
const { sign, whole, fraction } = parseDecimal(raw, value);
|
|
122
|
+
assertExactPrecision(fraction, fractionDigits, value);
|
|
123
|
+
const scaled = scaleDecimal(whole, fraction, fractionDigits, value);
|
|
124
|
+
return (sign === "-" ? -1 : 1) * scaled;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Converts integer minor units into a decimal string.
|
|
128
|
+
*
|
|
129
|
+
* @param minorUnits - Amount in minor units.
|
|
130
|
+
* @param options - Conversion options.
|
|
131
|
+
* @param options.fractionDigits - Digits to render. Defaults to 2.
|
|
132
|
+
* @returns The decimal amount, with exactly `fractionDigits` digits.
|
|
133
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* toDecimal(1999); // "19.99"
|
|
137
|
+
*/
|
|
138
|
+
function toDecimal(minorUnits, options = {}) {
|
|
139
|
+
assertMinorUnits(minorUnits);
|
|
140
|
+
const fractionDigits = options.fractionDigits ?? 2;
|
|
141
|
+
assertFractionDigits(fractionDigits);
|
|
142
|
+
const negative = minorUnits < 0;
|
|
143
|
+
const digits = String(Math.abs(minorUnits)).padStart(fractionDigits + 1, "0");
|
|
144
|
+
const whole = digits.slice(0, digits.length - fractionDigits);
|
|
145
|
+
const fraction = fractionDigits === 0 ? "" : `.${digits.slice(digits.length - fractionDigits)}`;
|
|
146
|
+
return `${negative ? "-" : ""}${whole}${fraction}`;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Adds two amounts in minor units.
|
|
150
|
+
*
|
|
151
|
+
* @param left - First amount.
|
|
152
|
+
* @param right - Second amount.
|
|
153
|
+
* @returns The sum.
|
|
154
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
155
|
+
*/
|
|
156
|
+
function addMoney(left, right) {
|
|
157
|
+
assertMinorUnits(left, "left");
|
|
158
|
+
assertMinorUnits(right, "right");
|
|
159
|
+
const sum = left + right;
|
|
160
|
+
assertMinorUnits(sum, "the sum");
|
|
161
|
+
return sum;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Subtracts two amounts in minor units.
|
|
165
|
+
*
|
|
166
|
+
* @param left - Amount to subtract from.
|
|
167
|
+
* @param right - Amount to subtract.
|
|
168
|
+
* @returns The difference.
|
|
169
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
170
|
+
*/
|
|
171
|
+
function subtractMoney(left, right) {
|
|
172
|
+
assertMinorUnits(left, "left");
|
|
173
|
+
assertMinorUnits(right, "right");
|
|
174
|
+
const difference = left - right;
|
|
175
|
+
assertMinorUnits(difference, "the difference");
|
|
176
|
+
return difference;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Adds a list of amounts in minor units.
|
|
180
|
+
*
|
|
181
|
+
* @param amounts - Amounts to add.
|
|
182
|
+
* @returns The sum, or `0` for an empty list.
|
|
183
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
184
|
+
*/
|
|
185
|
+
function sumMoney(amounts) {
|
|
186
|
+
if (!Array.isArray(amounts)) {
|
|
187
|
+
fail("MONEY_INVALID_MINOR_UNITS", "Expected amounts to be an array.", { received: typeof amounts });
|
|
188
|
+
}
|
|
189
|
+
return amounts.reduce((total, amount) => addMoney(total, amount), 0);
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Multiplies an amount by a factor, settling any fraction with an explicit rounding mode.
|
|
193
|
+
*
|
|
194
|
+
* @param minorUnits - Amount in minor units.
|
|
195
|
+
* @param factor - Multiplier.
|
|
196
|
+
* @param options - Rounding options.
|
|
197
|
+
* @param options.rounding - Rounding mode, defaults to `half-away-from-zero`.
|
|
198
|
+
* @returns The product in minor units.
|
|
199
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
|
|
200
|
+
*
|
|
201
|
+
* @example
|
|
202
|
+
* multiplyMoney(1999, 3); // 5997
|
|
203
|
+
*/
|
|
204
|
+
function multiplyMoney(minorUnits, factor, options = {}) {
|
|
205
|
+
assertMinorUnits(minorUnits);
|
|
206
|
+
assertFactor(factor);
|
|
207
|
+
const rounding = options.rounding ?? "half-away-from-zero";
|
|
208
|
+
if (!ROUNDING_MODES.includes(rounding)) {
|
|
209
|
+
fail("MONEY_INVALID_FACTOR", `Expected rounding to be one of: ${ROUNDING_MODES.join(", ")}.`, {
|
|
210
|
+
received: rounding
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
// Reduce the factor to an integer ratio so the product stays in integer space.
|
|
214
|
+
const scale = 10 ** countDecimals(factor);
|
|
215
|
+
const numerator = Math.round(factor * scale);
|
|
216
|
+
const result = round((minorUnits * numerator) / scale, rounding);
|
|
217
|
+
assertMinorUnits(result, "the product");
|
|
218
|
+
return result;
|
|
219
|
+
}
|
|
220
|
+
function countDecimals(value) {
|
|
221
|
+
const text = String(value);
|
|
222
|
+
const dot = text.indexOf(".");
|
|
223
|
+
if (dot === -1)
|
|
224
|
+
return 0;
|
|
225
|
+
return Math.min(text.length - dot - 1, 12);
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Returns the percentage of an amount, in minor units.
|
|
229
|
+
*
|
|
230
|
+
* @param minorUnits - Amount in minor units.
|
|
231
|
+
* @param percent - Percentage, for example `19` for 19%.
|
|
232
|
+
* @param options - Rounding options.
|
|
233
|
+
* @returns The percentage amount.
|
|
234
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
|
|
235
|
+
*
|
|
236
|
+
* @example
|
|
237
|
+
* percentageOf(10000, 19); // 1900
|
|
238
|
+
*/
|
|
239
|
+
function percentageOf(minorUnits, percent, options = {}) {
|
|
240
|
+
assertMinorUnits(minorUnits);
|
|
241
|
+
assertFactor(percent, "percent");
|
|
242
|
+
return multiplyMoney(minorUnits, percent / 100, options);
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Applies a percentage to an amount, adding it for a positive value and subtracting for a negative one.
|
|
246
|
+
*
|
|
247
|
+
* @param minorUnits - Amount in minor units.
|
|
248
|
+
* @param percent - Percentage. `-10` applies a 10% discount.
|
|
249
|
+
* @param options - Rounding options.
|
|
250
|
+
* @returns The adjusted amount.
|
|
251
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* applyPercentage(10000, 21); // 12100
|
|
255
|
+
* applyPercentage(10000, -10); // 9000
|
|
256
|
+
*/
|
|
257
|
+
function applyPercentage(minorUnits, percent, options = {}) {
|
|
258
|
+
return addMoney(minorUnits, percentageOf(minorUnits, percent, options));
|
|
259
|
+
}
|
|
260
|
+
function assertWeights(weights) {
|
|
261
|
+
if (!Array.isArray(weights) || weights.length === 0) {
|
|
262
|
+
fail("MONEY_INVALID_WEIGHTS", "Expected a non-empty array of weights.", { received: weights });
|
|
263
|
+
}
|
|
264
|
+
for (const weight of weights) {
|
|
265
|
+
if (typeof weight !== "number" || !Number.isFinite(weight) || weight < 0 || !Number.isInteger(weight)) {
|
|
266
|
+
fail("MONEY_INVALID_WEIGHTS", "Expected every weight to be a non-negative integer.", { received: weight });
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
function weightSumOrFail(weights) {
|
|
271
|
+
const weightSum = weights.reduce((sum, weight) => sum + weight, 0);
|
|
272
|
+
if (weightSum === 0) {
|
|
273
|
+
fail("MONEY_INVALID_WEIGHTS", "Expected the weights to sum above zero.", { weights });
|
|
274
|
+
}
|
|
275
|
+
return weightSum;
|
|
276
|
+
}
|
|
277
|
+
function planShares(weights, magnitude, weightSum) {
|
|
278
|
+
// Exact share times the weight, kept as a numerator so no precision is lost.
|
|
279
|
+
const scale = 10 ** 9;
|
|
280
|
+
const shares = weights.map((weight) => (weight * magnitude * scale) / weightSum);
|
|
281
|
+
const floors = shares.map((share) => Math.floor(share / scale));
|
|
282
|
+
// Hand the leftover units to the largest fractional shares first, earliest part winning a tie.
|
|
283
|
+
const order = shares
|
|
284
|
+
.map((share, index) => ({ index, fraction: (share / scale) % 1 }))
|
|
285
|
+
.sort((a, b) => b.fraction - a.fraction || a.index - b.index);
|
|
286
|
+
return { floors, order };
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Splits an amount across weights without losing or inventing a single minor unit.
|
|
290
|
+
*
|
|
291
|
+
* Uses the largest-remainder method, so the parts always sum back to the total exactly. Each extra
|
|
292
|
+
* minor unit goes to the earliest parts, which keeps the result deterministic.
|
|
293
|
+
*
|
|
294
|
+
* @param total - Amount in minor units.
|
|
295
|
+
* @param weights - Non-negative whole-number weights, one per part.
|
|
296
|
+
* @returns One amount per weight, summing exactly to `total`.
|
|
297
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_WEIGHTS`.
|
|
298
|
+
*
|
|
299
|
+
* @example
|
|
300
|
+
* allocateAmount(1000, [1, 1, 1]); // [334, 333, 333]
|
|
301
|
+
*/
|
|
302
|
+
function allocateAmount(total, weights) {
|
|
303
|
+
assertMinorUnits(total, "total");
|
|
304
|
+
assertWeights(weights);
|
|
305
|
+
const weightSum = weightSumOrFail(weights);
|
|
306
|
+
const sign = total < 0 ? -1 : 1;
|
|
307
|
+
const magnitude = Math.abs(total);
|
|
308
|
+
const { floors, order } = planShares(weights, magnitude, weightSum);
|
|
309
|
+
let remainder = magnitude - floors.reduce((sum, value) => sum + value, 0);
|
|
310
|
+
const result = [...floors];
|
|
311
|
+
for (const { index } of order) {
|
|
312
|
+
if (remainder <= 0)
|
|
313
|
+
break;
|
|
314
|
+
result[index] += 1;
|
|
315
|
+
remainder -= 1;
|
|
316
|
+
}
|
|
317
|
+
return result.map((value) => sign * value);
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Formats an amount for display.
|
|
321
|
+
*
|
|
322
|
+
* @param minorUnits - Amount in minor units.
|
|
323
|
+
* @param options - Formatting options.
|
|
324
|
+
* @param options.currency - ISO 4217 code, defaults to `USD`.
|
|
325
|
+
* @param options.locale - BCP 47 tag, defaults to `en-US`.
|
|
326
|
+
* @param options.showCurrency - Omit the symbol or code, defaults to `true`.
|
|
327
|
+
* @param options.signed - Force an explicit `+` on a positive amount, defaults to `false`.
|
|
328
|
+
* @returns The formatted string.
|
|
329
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
330
|
+
*
|
|
331
|
+
* @example
|
|
332
|
+
* formatMoney(123456); // "$1,234.56"
|
|
333
|
+
*/
|
|
334
|
+
function formatMoney(minorUnits, options = {}) {
|
|
335
|
+
assertMinorUnits(minorUnits);
|
|
336
|
+
const currency = options.currency ?? "USD";
|
|
337
|
+
const locale = options.locale ?? "en-US";
|
|
338
|
+
const fractionDigits = resolveFractionDigits(currency, locale);
|
|
339
|
+
// Intl decides the fraction digits for a currency, so ask it, then hand the count back so the
|
|
340
|
+
// decimal style keeps its trailing zeros instead of defaulting to Intl's maximum of 3.
|
|
341
|
+
const formatter = new Intl.NumberFormat(locale, {
|
|
342
|
+
style: options.showCurrency === false ? "decimal" : "currency",
|
|
343
|
+
...(options.showCurrency === false ? {} : { currency }),
|
|
344
|
+
minimumFractionDigits: fractionDigits,
|
|
345
|
+
maximumFractionDigits: fractionDigits,
|
|
346
|
+
signDisplay: options.signed ? "exceptZero" : "auto"
|
|
347
|
+
});
|
|
348
|
+
return formatter.format(Number(toDecimal(minorUnits, { fractionDigits })));
|
|
349
|
+
}
|
|
350
|
+
function resolveFractionDigits(currency, locale) {
|
|
351
|
+
try {
|
|
352
|
+
const parts = new Intl.NumberFormat(locale, { style: "currency", currency }).formatToParts(1);
|
|
353
|
+
const fraction = parts.find((part) => part.type === "fraction")?.value ?? "";
|
|
354
|
+
return fraction.replace(/\D/g, "").length;
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
// An unusable currency or locale falls back to the common two digits.
|
|
358
|
+
return 2;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AA4JA,kCAaC;AAcD,8BAYC;AAUD,4BAMC;AAUD,sCAMC;AASD,4BAKC;AAeD,sCAkBC;AAqBD,oCAIC;AAeD,0CAEC;AAkDD,wCAkBC;AAiBD,kCAkBC;AA3ZD;;;;GAIG;AACH,MAAa,UAAW,SAAQ,KAAK;IAInC,YAAY,IAAoB,EAAE,OAAe,EAAE,UAAmC,EAAE;QACtF,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,UAAU,CAAC,SAAS,CAAC,CAAC;IACpD,CAAC;CACF;AAXD,gCAWC;AAED,SAAS,IAAI,CAAC,IAAoB,EAAE,OAAe,EAAE,UAAmC,EAAE;IACxF,MAAM,IAAI,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;AAC/C,CAAC;AAKD,MAAM,cAAc,GAAmB,CAAC,qBAAqB,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAEnG,+FAA+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C,MAAM,CAAC;QACP,sEAAsE;QACtE,OAAO,CAAC,CAAC;IACX,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/** Stable money error codes. */
|
|
2
|
+
export type MoneyErrorCode = "MONEY_INVALID_DECIMAL" | "MONEY_INVALID_MINOR_UNITS" | "MONEY_INVALID_FACTOR" | "MONEY_INVALID_WEIGHTS" | "MONEY_INVALID_FRACTION_DIGITS";
|
|
3
|
+
/**
|
|
4
|
+
* Error thrown by the money utilities.
|
|
5
|
+
*
|
|
6
|
+
* Carries a stable machine-readable `code` and a `details` context object.
|
|
7
|
+
*/
|
|
8
|
+
export declare class MoneyError extends Error {
|
|
9
|
+
readonly code: MoneyErrorCode;
|
|
10
|
+
readonly details: Record<string, unknown>;
|
|
11
|
+
constructor(code: MoneyErrorCode, message: string, details?: Record<string, unknown>);
|
|
12
|
+
}
|
|
13
|
+
/** Rounding behaviour for a fractional result. */
|
|
14
|
+
export type RoundingMode = "half-away-from-zero" | "half-up" | "floor" | "ceil" | "down";
|
|
15
|
+
/** Options for {@link fromDecimal}. */
|
|
16
|
+
export type FromDecimalOptions = {
|
|
17
|
+
/** Digits the currency supports. Defaults to 2. More than this is refused. */
|
|
18
|
+
fractionDigits?: number;
|
|
19
|
+
};
|
|
20
|
+
/** Options for {@link toDecimal}. */
|
|
21
|
+
export type ToDecimalOptions = {
|
|
22
|
+
/** Digits to render. Defaults to 2. */
|
|
23
|
+
fractionDigits?: number;
|
|
24
|
+
};
|
|
25
|
+
/** Options for {@link multiplyMoney}, {@link percentageOf} and {@link applyPercentage}. */
|
|
26
|
+
export type MultiplyOptions = {
|
|
27
|
+
/** How to settle a fractional minor unit. Defaults to `half-away-from-zero`. */
|
|
28
|
+
rounding?: RoundingMode;
|
|
29
|
+
};
|
|
30
|
+
/** Options for {@link formatMoney}. */
|
|
31
|
+
export type FormatMoneyOptions = {
|
|
32
|
+
/** ISO 4217 currency code. */
|
|
33
|
+
currency?: string;
|
|
34
|
+
/** BCP 47 locale tag. */
|
|
35
|
+
locale?: string;
|
|
36
|
+
/** Omit the currency symbol or code. */
|
|
37
|
+
showCurrency?: boolean;
|
|
38
|
+
/** Force an explicit `+` on a positive amount. */
|
|
39
|
+
signed?: boolean;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Converts a decimal amount into integer minor units.
|
|
43
|
+
*
|
|
44
|
+
* Parsing the decimal as a string keeps the conversion exact: `"2.675"` becomes `268` minor units
|
|
45
|
+
* for a two-digit currency rather than inheriting the float `2.674999...`.
|
|
46
|
+
*
|
|
47
|
+
* @param value - Decimal amount as a string, or a number you already trust.
|
|
48
|
+
* @param options - Conversion options.
|
|
49
|
+
* @param options.fractionDigits - Digits the currency supports. Defaults to 2.
|
|
50
|
+
* @returns Amount in minor units.
|
|
51
|
+
* @throws {MoneyError} `MONEY_INVALID_DECIMAL` or `MONEY_INVALID_FRACTION_DIGITS`.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* fromDecimal("19.99"); // 1999
|
|
55
|
+
* fromDecimal("0.07"); // 7
|
|
56
|
+
*/
|
|
57
|
+
export declare function fromDecimal(value: string | number, options?: FromDecimalOptions): number;
|
|
58
|
+
/**
|
|
59
|
+
* Converts integer minor units into a decimal string.
|
|
60
|
+
*
|
|
61
|
+
* @param minorUnits - Amount in minor units.
|
|
62
|
+
* @param options - Conversion options.
|
|
63
|
+
* @param options.fractionDigits - Digits to render. Defaults to 2.
|
|
64
|
+
* @returns The decimal amount, with exactly `fractionDigits` digits.
|
|
65
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* toDecimal(1999); // "19.99"
|
|
69
|
+
*/
|
|
70
|
+
export declare function toDecimal(minorUnits: number, options?: ToDecimalOptions): string;
|
|
71
|
+
/**
|
|
72
|
+
* Adds two amounts in minor units.
|
|
73
|
+
*
|
|
74
|
+
* @param left - First amount.
|
|
75
|
+
* @param right - Second amount.
|
|
76
|
+
* @returns The sum.
|
|
77
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
78
|
+
*/
|
|
79
|
+
export declare function addMoney(left: number, right: number): number;
|
|
80
|
+
/**
|
|
81
|
+
* Subtracts two amounts in minor units.
|
|
82
|
+
*
|
|
83
|
+
* @param left - Amount to subtract from.
|
|
84
|
+
* @param right - Amount to subtract.
|
|
85
|
+
* @returns The difference.
|
|
86
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
87
|
+
*/
|
|
88
|
+
export declare function subtractMoney(left: number, right: number): number;
|
|
89
|
+
/**
|
|
90
|
+
* Adds a list of amounts in minor units.
|
|
91
|
+
*
|
|
92
|
+
* @param amounts - Amounts to add.
|
|
93
|
+
* @returns The sum, or `0` for an empty list.
|
|
94
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
95
|
+
*/
|
|
96
|
+
export declare function sumMoney(amounts: readonly number[]): number;
|
|
97
|
+
/**
|
|
98
|
+
* Multiplies an amount by a factor, settling any fraction with an explicit rounding mode.
|
|
99
|
+
*
|
|
100
|
+
* @param minorUnits - Amount in minor units.
|
|
101
|
+
* @param factor - Multiplier.
|
|
102
|
+
* @param options - Rounding options.
|
|
103
|
+
* @param options.rounding - Rounding mode, defaults to `half-away-from-zero`.
|
|
104
|
+
* @returns The product in minor units.
|
|
105
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
|
|
106
|
+
*
|
|
107
|
+
* @example
|
|
108
|
+
* multiplyMoney(1999, 3); // 5997
|
|
109
|
+
*/
|
|
110
|
+
export declare function multiplyMoney(minorUnits: number, factor: number, options?: MultiplyOptions): number;
|
|
111
|
+
/**
|
|
112
|
+
* Returns the percentage of an amount, in minor units.
|
|
113
|
+
*
|
|
114
|
+
* @param minorUnits - Amount in minor units.
|
|
115
|
+
* @param percent - Percentage, for example `19` for 19%.
|
|
116
|
+
* @param options - Rounding options.
|
|
117
|
+
* @returns The percentage amount.
|
|
118
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* percentageOf(10000, 19); // 1900
|
|
122
|
+
*/
|
|
123
|
+
export declare function percentageOf(minorUnits: number, percent: number, options?: MultiplyOptions): number;
|
|
124
|
+
/**
|
|
125
|
+
* Applies a percentage to an amount, adding it for a positive value and subtracting for a negative one.
|
|
126
|
+
*
|
|
127
|
+
* @param minorUnits - Amount in minor units.
|
|
128
|
+
* @param percent - Percentage. `-10` applies a 10% discount.
|
|
129
|
+
* @param options - Rounding options.
|
|
130
|
+
* @returns The adjusted amount.
|
|
131
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
|
|
132
|
+
*
|
|
133
|
+
* @example
|
|
134
|
+
* applyPercentage(10000, 21); // 12100
|
|
135
|
+
* applyPercentage(10000, -10); // 9000
|
|
136
|
+
*/
|
|
137
|
+
export declare function applyPercentage(minorUnits: number, percent: number, options?: MultiplyOptions): number;
|
|
138
|
+
/**
|
|
139
|
+
* Splits an amount across weights without losing or inventing a single minor unit.
|
|
140
|
+
*
|
|
141
|
+
* Uses the largest-remainder method, so the parts always sum back to the total exactly. Each extra
|
|
142
|
+
* minor unit goes to the earliest parts, which keeps the result deterministic.
|
|
143
|
+
*
|
|
144
|
+
* @param total - Amount in minor units.
|
|
145
|
+
* @param weights - Non-negative whole-number weights, one per part.
|
|
146
|
+
* @returns One amount per weight, summing exactly to `total`.
|
|
147
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_WEIGHTS`.
|
|
148
|
+
*
|
|
149
|
+
* @example
|
|
150
|
+
* allocateAmount(1000, [1, 1, 1]); // [334, 333, 333]
|
|
151
|
+
*/
|
|
152
|
+
export declare function allocateAmount(total: number, weights: readonly number[]): number[];
|
|
153
|
+
/**
|
|
154
|
+
* Formats an amount for display.
|
|
155
|
+
*
|
|
156
|
+
* @param minorUnits - Amount in minor units.
|
|
157
|
+
* @param options - Formatting options.
|
|
158
|
+
* @param options.currency - ISO 4217 code, defaults to `USD`.
|
|
159
|
+
* @param options.locale - BCP 47 tag, defaults to `en-US`.
|
|
160
|
+
* @param options.showCurrency - Omit the symbol or code, defaults to `true`.
|
|
161
|
+
* @param options.signed - Force an explicit `+` on a positive amount, defaults to `false`.
|
|
162
|
+
* @returns The formatted string.
|
|
163
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
164
|
+
*
|
|
165
|
+
* @example
|
|
166
|
+
* formatMoney(123456); // "$1,234.56"
|
|
167
|
+
*/
|
|
168
|
+
export declare function formatMoney(minorUnits: number, options?: FormatMoneyOptions): string;
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error thrown by the money utilities.
|
|
3
|
+
*
|
|
4
|
+
* Carries a stable machine-readable `code` and a `details` context object.
|
|
5
|
+
*/
|
|
6
|
+
export class MoneyError extends Error {
|
|
7
|
+
constructor(code, message, details = {}) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "MoneyError";
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.details = details;
|
|
12
|
+
Object.setPrototypeOf(this, MoneyError.prototype);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function fail(code, message, details = {}) {
|
|
16
|
+
throw new MoneyError(code, message, details);
|
|
17
|
+
}
|
|
18
|
+
const ROUNDING_MODES = ["half-away-from-zero", "half-up", "floor", "ceil", "down"];
|
|
19
|
+
// A plain decimal string. Deliberately narrow: no exponent, no currency symbol, no separators.
|
|
20
|
+
// eslint-disable-next-line security/detect-unsafe-regex -- anchored, no nested quantifier
|
|
21
|
+
const DECIMAL = /^(-?)(\d+)(?:\.(\d+))?$/;
|
|
22
|
+
function assertFractionDigits(value) {
|
|
23
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
24
|
+
fail("MONEY_INVALID_FRACTION_DIGITS", "Expected fractionDigits to be a non-negative integer.", {
|
|
25
|
+
received: value
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function assertMinorUnits(value, label = "minor units") {
|
|
30
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) {
|
|
31
|
+
fail("MONEY_INVALID_MINOR_UNITS", `Expected ${label} to be a safe integer.`, { received: value });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function assertFactor(value, label = "factor") {
|
|
35
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
36
|
+
fail("MONEY_INVALID_FACTOR", `Expected ${label} to be a finite number.`, { received: value });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function round(value, mode) {
|
|
40
|
+
switch (mode) {
|
|
41
|
+
case "floor":
|
|
42
|
+
return Math.floor(value);
|
|
43
|
+
case "ceil":
|
|
44
|
+
return Math.ceil(value);
|
|
45
|
+
case "down":
|
|
46
|
+
// Toward zero, unlike floor on a negative result.
|
|
47
|
+
return value < 0 ? Math.ceil(value) : Math.floor(value);
|
|
48
|
+
case "half-up":
|
|
49
|
+
// Ties go toward positive infinity, so -0.5 settles to 0.
|
|
50
|
+
return Math.round(value);
|
|
51
|
+
default:
|
|
52
|
+
// Half away from zero, which is what invoices and tax tables expect.
|
|
53
|
+
return value < 0 ? -Math.round(-value) : Math.round(value);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function parseDecimal(raw, value) {
|
|
57
|
+
const match = raw.trim().match(DECIMAL);
|
|
58
|
+
if (!match) {
|
|
59
|
+
fail("MONEY_INVALID_DECIMAL", `Expected a plain decimal amount, received ${JSON.stringify(value)}.`, {
|
|
60
|
+
received: value
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
const [, sign, whole, fraction = ""] = match;
|
|
64
|
+
return { sign, whole, fraction };
|
|
65
|
+
}
|
|
66
|
+
function assertExactPrecision(fraction, fractionDigits, value) {
|
|
67
|
+
// Conversion is exact or refused. Rounding an input amount silently is how an invoice dispute
|
|
68
|
+
// starts, so anything beyond the currency's own precision is an error rather than a rounded value.
|
|
69
|
+
if (/[^0]/.test(fraction.slice(fractionDigits))) {
|
|
70
|
+
fail("MONEY_INVALID_DECIMAL", `Expected at most ${fractionDigits} fraction digits.`, {
|
|
71
|
+
received: value,
|
|
72
|
+
fractionDigits
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function scaleDecimal(whole, fraction, fractionDigits, value) {
|
|
77
|
+
const kept = fraction.padEnd(fractionDigits, "0").slice(0, fractionDigits);
|
|
78
|
+
const scaled = Number(`${whole}${kept}`);
|
|
79
|
+
if (!Number.isSafeInteger(scaled)) {
|
|
80
|
+
fail("MONEY_INVALID_DECIMAL", "Expected an amount within the safe integer range.", { received: value });
|
|
81
|
+
}
|
|
82
|
+
return scaled;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Converts a decimal amount into integer minor units.
|
|
86
|
+
*
|
|
87
|
+
* Parsing the decimal as a string keeps the conversion exact: `"2.675"` becomes `268` minor units
|
|
88
|
+
* for a two-digit currency rather than inheriting the float `2.674999...`.
|
|
89
|
+
*
|
|
90
|
+
* @param value - Decimal amount as a string, or a number you already trust.
|
|
91
|
+
* @param options - Conversion options.
|
|
92
|
+
* @param options.fractionDigits - Digits the currency supports. Defaults to 2.
|
|
93
|
+
* @returns Amount in minor units.
|
|
94
|
+
* @throws {MoneyError} `MONEY_INVALID_DECIMAL` or `MONEY_INVALID_FRACTION_DIGITS`.
|
|
95
|
+
*
|
|
96
|
+
* @example
|
|
97
|
+
* fromDecimal("19.99"); // 1999
|
|
98
|
+
* fromDecimal("0.07"); // 7
|
|
99
|
+
*/
|
|
100
|
+
export function fromDecimal(value, options = {}) {
|
|
101
|
+
const fractionDigits = options.fractionDigits ?? 2;
|
|
102
|
+
assertFractionDigits(fractionDigits);
|
|
103
|
+
const raw = typeof value === "number" ? value.toString() : value;
|
|
104
|
+
if (typeof raw !== "string") {
|
|
105
|
+
fail("MONEY_INVALID_DECIMAL", "Expected a decimal string or a number.", { received: typeof value });
|
|
106
|
+
}
|
|
107
|
+
const { sign, whole, fraction } = parseDecimal(raw, value);
|
|
108
|
+
assertExactPrecision(fraction, fractionDigits, value);
|
|
109
|
+
const scaled = scaleDecimal(whole, fraction, fractionDigits, value);
|
|
110
|
+
return (sign === "-" ? -1 : 1) * scaled;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Converts integer minor units into a decimal string.
|
|
114
|
+
*
|
|
115
|
+
* @param minorUnits - Amount in minor units.
|
|
116
|
+
* @param options - Conversion options.
|
|
117
|
+
* @param options.fractionDigits - Digits to render. Defaults to 2.
|
|
118
|
+
* @returns The decimal amount, with exactly `fractionDigits` digits.
|
|
119
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* toDecimal(1999); // "19.99"
|
|
123
|
+
*/
|
|
124
|
+
export function toDecimal(minorUnits, options = {}) {
|
|
125
|
+
assertMinorUnits(minorUnits);
|
|
126
|
+
const fractionDigits = options.fractionDigits ?? 2;
|
|
127
|
+
assertFractionDigits(fractionDigits);
|
|
128
|
+
const negative = minorUnits < 0;
|
|
129
|
+
const digits = String(Math.abs(minorUnits)).padStart(fractionDigits + 1, "0");
|
|
130
|
+
const whole = digits.slice(0, digits.length - fractionDigits);
|
|
131
|
+
const fraction = fractionDigits === 0 ? "" : `.${digits.slice(digits.length - fractionDigits)}`;
|
|
132
|
+
return `${negative ? "-" : ""}${whole}${fraction}`;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Adds two amounts in minor units.
|
|
136
|
+
*
|
|
137
|
+
* @param left - First amount.
|
|
138
|
+
* @param right - Second amount.
|
|
139
|
+
* @returns The sum.
|
|
140
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
141
|
+
*/
|
|
142
|
+
export function addMoney(left, right) {
|
|
143
|
+
assertMinorUnits(left, "left");
|
|
144
|
+
assertMinorUnits(right, "right");
|
|
145
|
+
const sum = left + right;
|
|
146
|
+
assertMinorUnits(sum, "the sum");
|
|
147
|
+
return sum;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Subtracts two amounts in minor units.
|
|
151
|
+
*
|
|
152
|
+
* @param left - Amount to subtract from.
|
|
153
|
+
* @param right - Amount to subtract.
|
|
154
|
+
* @returns The difference.
|
|
155
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
156
|
+
*/
|
|
157
|
+
export function subtractMoney(left, right) {
|
|
158
|
+
assertMinorUnits(left, "left");
|
|
159
|
+
assertMinorUnits(right, "right");
|
|
160
|
+
const difference = left - right;
|
|
161
|
+
assertMinorUnits(difference, "the difference");
|
|
162
|
+
return difference;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Adds a list of amounts in minor units.
|
|
166
|
+
*
|
|
167
|
+
* @param amounts - Amounts to add.
|
|
168
|
+
* @returns The sum, or `0` for an empty list.
|
|
169
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
170
|
+
*/
|
|
171
|
+
export function sumMoney(amounts) {
|
|
172
|
+
if (!Array.isArray(amounts)) {
|
|
173
|
+
fail("MONEY_INVALID_MINOR_UNITS", "Expected amounts to be an array.", { received: typeof amounts });
|
|
174
|
+
}
|
|
175
|
+
return amounts.reduce((total, amount) => addMoney(total, amount), 0);
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Multiplies an amount by a factor, settling any fraction with an explicit rounding mode.
|
|
179
|
+
*
|
|
180
|
+
* @param minorUnits - Amount in minor units.
|
|
181
|
+
* @param factor - Multiplier.
|
|
182
|
+
* @param options - Rounding options.
|
|
183
|
+
* @param options.rounding - Rounding mode, defaults to `half-away-from-zero`.
|
|
184
|
+
* @returns The product in minor units.
|
|
185
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
|
|
186
|
+
*
|
|
187
|
+
* @example
|
|
188
|
+
* multiplyMoney(1999, 3); // 5997
|
|
189
|
+
*/
|
|
190
|
+
export function multiplyMoney(minorUnits, factor, options = {}) {
|
|
191
|
+
assertMinorUnits(minorUnits);
|
|
192
|
+
assertFactor(factor);
|
|
193
|
+
const rounding = options.rounding ?? "half-away-from-zero";
|
|
194
|
+
if (!ROUNDING_MODES.includes(rounding)) {
|
|
195
|
+
fail("MONEY_INVALID_FACTOR", `Expected rounding to be one of: ${ROUNDING_MODES.join(", ")}.`, {
|
|
196
|
+
received: rounding
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
// Reduce the factor to an integer ratio so the product stays in integer space.
|
|
200
|
+
const scale = 10 ** countDecimals(factor);
|
|
201
|
+
const numerator = Math.round(factor * scale);
|
|
202
|
+
const result = round((minorUnits * numerator) / scale, rounding);
|
|
203
|
+
assertMinorUnits(result, "the product");
|
|
204
|
+
return result;
|
|
205
|
+
}
|
|
206
|
+
function countDecimals(value) {
|
|
207
|
+
const text = String(value);
|
|
208
|
+
const dot = text.indexOf(".");
|
|
209
|
+
if (dot === -1)
|
|
210
|
+
return 0;
|
|
211
|
+
return Math.min(text.length - dot - 1, 12);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Returns the percentage of an amount, in minor units.
|
|
215
|
+
*
|
|
216
|
+
* @param minorUnits - Amount in minor units.
|
|
217
|
+
* @param percent - Percentage, for example `19` for 19%.
|
|
218
|
+
* @param options - Rounding options.
|
|
219
|
+
* @returns The percentage amount.
|
|
220
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
|
|
221
|
+
*
|
|
222
|
+
* @example
|
|
223
|
+
* percentageOf(10000, 19); // 1900
|
|
224
|
+
*/
|
|
225
|
+
export function percentageOf(minorUnits, percent, options = {}) {
|
|
226
|
+
assertMinorUnits(minorUnits);
|
|
227
|
+
assertFactor(percent, "percent");
|
|
228
|
+
return multiplyMoney(minorUnits, percent / 100, options);
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Applies a percentage to an amount, adding it for a positive value and subtracting for a negative one.
|
|
232
|
+
*
|
|
233
|
+
* @param minorUnits - Amount in minor units.
|
|
234
|
+
* @param percent - Percentage. `-10` applies a 10% discount.
|
|
235
|
+
* @param options - Rounding options.
|
|
236
|
+
* @returns The adjusted amount.
|
|
237
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_FACTOR`.
|
|
238
|
+
*
|
|
239
|
+
* @example
|
|
240
|
+
* applyPercentage(10000, 21); // 12100
|
|
241
|
+
* applyPercentage(10000, -10); // 9000
|
|
242
|
+
*/
|
|
243
|
+
export function applyPercentage(minorUnits, percent, options = {}) {
|
|
244
|
+
return addMoney(minorUnits, percentageOf(minorUnits, percent, options));
|
|
245
|
+
}
|
|
246
|
+
function assertWeights(weights) {
|
|
247
|
+
if (!Array.isArray(weights) || weights.length === 0) {
|
|
248
|
+
fail("MONEY_INVALID_WEIGHTS", "Expected a non-empty array of weights.", { received: weights });
|
|
249
|
+
}
|
|
250
|
+
for (const weight of weights) {
|
|
251
|
+
if (typeof weight !== "number" || !Number.isFinite(weight) || weight < 0 || !Number.isInteger(weight)) {
|
|
252
|
+
fail("MONEY_INVALID_WEIGHTS", "Expected every weight to be a non-negative integer.", { received: weight });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
function weightSumOrFail(weights) {
|
|
257
|
+
const weightSum = weights.reduce((sum, weight) => sum + weight, 0);
|
|
258
|
+
if (weightSum === 0) {
|
|
259
|
+
fail("MONEY_INVALID_WEIGHTS", "Expected the weights to sum above zero.", { weights });
|
|
260
|
+
}
|
|
261
|
+
return weightSum;
|
|
262
|
+
}
|
|
263
|
+
function planShares(weights, magnitude, weightSum) {
|
|
264
|
+
// Exact share times the weight, kept as a numerator so no precision is lost.
|
|
265
|
+
const scale = 10 ** 9;
|
|
266
|
+
const shares = weights.map((weight) => (weight * magnitude * scale) / weightSum);
|
|
267
|
+
const floors = shares.map((share) => Math.floor(share / scale));
|
|
268
|
+
// Hand the leftover units to the largest fractional shares first, earliest part winning a tie.
|
|
269
|
+
const order = shares
|
|
270
|
+
.map((share, index) => ({ index, fraction: (share / scale) % 1 }))
|
|
271
|
+
.sort((a, b) => b.fraction - a.fraction || a.index - b.index);
|
|
272
|
+
return { floors, order };
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Splits an amount across weights without losing or inventing a single minor unit.
|
|
276
|
+
*
|
|
277
|
+
* Uses the largest-remainder method, so the parts always sum back to the total exactly. Each extra
|
|
278
|
+
* minor unit goes to the earliest parts, which keeps the result deterministic.
|
|
279
|
+
*
|
|
280
|
+
* @param total - Amount in minor units.
|
|
281
|
+
* @param weights - Non-negative whole-number weights, one per part.
|
|
282
|
+
* @returns One amount per weight, summing exactly to `total`.
|
|
283
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS` or `MONEY_INVALID_WEIGHTS`.
|
|
284
|
+
*
|
|
285
|
+
* @example
|
|
286
|
+
* allocateAmount(1000, [1, 1, 1]); // [334, 333, 333]
|
|
287
|
+
*/
|
|
288
|
+
export function allocateAmount(total, weights) {
|
|
289
|
+
assertMinorUnits(total, "total");
|
|
290
|
+
assertWeights(weights);
|
|
291
|
+
const weightSum = weightSumOrFail(weights);
|
|
292
|
+
const sign = total < 0 ? -1 : 1;
|
|
293
|
+
const magnitude = Math.abs(total);
|
|
294
|
+
const { floors, order } = planShares(weights, magnitude, weightSum);
|
|
295
|
+
let remainder = magnitude - floors.reduce((sum, value) => sum + value, 0);
|
|
296
|
+
const result = [...floors];
|
|
297
|
+
for (const { index } of order) {
|
|
298
|
+
if (remainder <= 0)
|
|
299
|
+
break;
|
|
300
|
+
result[index] += 1;
|
|
301
|
+
remainder -= 1;
|
|
302
|
+
}
|
|
303
|
+
return result.map((value) => sign * value);
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Formats an amount for display.
|
|
307
|
+
*
|
|
308
|
+
* @param minorUnits - Amount in minor units.
|
|
309
|
+
* @param options - Formatting options.
|
|
310
|
+
* @param options.currency - ISO 4217 code, defaults to `USD`.
|
|
311
|
+
* @param options.locale - BCP 47 tag, defaults to `en-US`.
|
|
312
|
+
* @param options.showCurrency - Omit the symbol or code, defaults to `true`.
|
|
313
|
+
* @param options.signed - Force an explicit `+` on a positive amount, defaults to `false`.
|
|
314
|
+
* @returns The formatted string.
|
|
315
|
+
* @throws {MoneyError} `MONEY_INVALID_MINOR_UNITS`.
|
|
316
|
+
*
|
|
317
|
+
* @example
|
|
318
|
+
* formatMoney(123456); // "$1,234.56"
|
|
319
|
+
*/
|
|
320
|
+
export function formatMoney(minorUnits, options = {}) {
|
|
321
|
+
assertMinorUnits(minorUnits);
|
|
322
|
+
const currency = options.currency ?? "USD";
|
|
323
|
+
const locale = options.locale ?? "en-US";
|
|
324
|
+
const fractionDigits = resolveFractionDigits(currency, locale);
|
|
325
|
+
// Intl decides the fraction digits for a currency, so ask it, then hand the count back so the
|
|
326
|
+
// decimal style keeps its trailing zeros instead of defaulting to Intl's maximum of 3.
|
|
327
|
+
const formatter = new Intl.NumberFormat(locale, {
|
|
328
|
+
style: options.showCurrency === false ? "decimal" : "currency",
|
|
329
|
+
...(options.showCurrency === false ? {} : { currency }),
|
|
330
|
+
minimumFractionDigits: fractionDigits,
|
|
331
|
+
maximumFractionDigits: fractionDigits,
|
|
332
|
+
signDisplay: options.signed ? "exceptZero" : "auto"
|
|
333
|
+
});
|
|
334
|
+
return formatter.format(Number(toDecimal(minorUnits, { fractionDigits })));
|
|
335
|
+
}
|
|
336
|
+
function resolveFractionDigits(currency, locale) {
|
|
337
|
+
try {
|
|
338
|
+
const parts = new Intl.NumberFormat(locale, { style: "currency", currency }).formatToParts(1);
|
|
339
|
+
const fraction = parts.find((part) => part.type === "fraction")?.value ?? "";
|
|
340
|
+
return fraction.replace(/\D/g, "").length;
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
// An unusable currency or locale falls back to the common two digits.
|
|
344
|
+
return 2;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAQA;;;;GAIG;AACH,MAAM,OAAO,UAAW,SAAQ,KAAK;IAInC,YAAY,IAAoB,EAAE,OAAe,EAAE,UAAmC,EAAE;QACtF,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,UAAU,CAAC,SAAS,CAAC,CAAC;IACpD,CAAC;CACF;AAED,SAAS,IAAI,CAAC,IAAoB,EAAE,OAAe,EAAE,UAAmC,EAAE;IACxF,MAAM,IAAI,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;AAC/C,CAAC;AAKD,MAAM,cAAc,GAAmB,CAAC,qBAAqB,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAEnG,+FAA+F;AAC/F,0FAA0F;AAC1F,MAAM,OAAO,GAAG,yBAAyB,CAAC;AAgC1C,SAAS,oBAAoB,CAAC,KAAc;IAC1C,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAK,KAAgB,GAAG,CAAC,EAAE,CAAC;QACtD,IAAI,CAAC,+BAA+B,EAAE,uDAAuD,EAAE;YAC7F,QAAQ,EAAE,KAAK;SAChB,CAAC,CAAC;I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
|
1
|
+
{
|
|
2
|
+
"name": "@jdsalasc/solvejs-money",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "TypeScript money utilities using integer minor units for lossless arithmetic, exact percentage application, largest-remainder allocation, and formatting, with no floating point rounding.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"main": "./dist/cjs/index.cjs",
|
|
9
|
+
"module": "./dist/esm/index.js",
|
|
10
|
+
"types": "./dist/esm/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/esm/index.d.ts",
|
|
14
|
+
"import": "./dist/esm/index.js",
|
|
15
|
+
"require": "./dist/cjs/index.cjs"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "npm run clean && npm run build:esm && npm run build:cjs",
|
|
24
|
+
"build:esm": "tsc -p tsconfig.esm.json",
|
|
25
|
+
"build:cjs": "tsc -p tsconfig.cjs.json && node ./scripts/rename-cjs.mjs",
|
|
26
|
+
"clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
|
|
27
|
+
"test": "npm run build && node --test test/*.test.mjs",
|
|
28
|
+
"lint": "tsc -p tsconfig.esm.json --noEmit"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"author": "jdsalasc",
|
|
34
|
+
"homepage": "https://github.com/jdsalasca/solvejs#readme",
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/jdsalasca/solvejs.git"
|
|
38
|
+
},
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/jdsalasca/solvejs/issues"
|
|
41
|
+
},
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=18"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {},
|
|
46
|
+
"keywords": [
|
|
47
|
+
"money",
|
|
48
|
+
"currency",
|
|
49
|
+
"minor units",
|
|
50
|
+
"cents",
|
|
51
|
+
"allocate",
|
|
52
|
+
"percentage",
|
|
53
|
+
"invoice",
|
|
54
|
+
"rounding",
|
|
55
|
+
"typescript",
|
|
56
|
+
"javascript",
|
|
57
|
+
"zero dependency",
|
|
58
|
+
"solvejs",
|
|
59
|
+
"esm",
|
|
60
|
+
"commonjs",
|
|
61
|
+
"nodejs",
|
|
62
|
+
"tree-shakeable",
|
|
63
|
+
"money library",
|
|
64
|
+
"currency math",
|
|
65
|
+
"split amount",
|
|
66
|
+
"financial calculations"
|
|
67
|
+
]
|
|
68
|
+
}
|