@pyreon/money 0.0.0-stage → 0.53.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/LICENSE +21 -0
- package/README.md +40 -2
- package/lib/_chunks/money-B9MhDL2i.js +551 -0
- package/lib/_chunks/money-B9MhDL2i.js.map +1 -0
- package/lib/_chunks/scaled-eXdrPpWS.js +195 -0
- package/lib/_chunks/scaled-eXdrPpWS.js.map +1 -0
- package/lib/decimal.js +126 -0
- package/lib/decimal.js.map +1 -0
- package/lib/fp.js +91 -0
- package/lib/fp.js.map +1 -0
- package/lib/index.js +3 -0
- package/lib/types/_dts_chunks/money-Cq-JWPjZ.d.ts +253 -0
- package/lib/types/_dts_chunks/scaled-vdrxv7sl.d.ts +3 -0
- package/lib/types/decimal.d.ts +83 -0
- package/lib/types/fp.d.ts +67 -0
- package/lib/types/index.d.ts +4 -0
- package/package.json +61 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-present Vit Bokisch
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,41 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pyreon/money
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **Status: Experimental.** Outside the semver promise: the API may change in a minor release. See the [stability policy](https://pyreon.dev/docs/stability-and-direction).
|
|
4
|
+
|
|
5
|
+
Exact amounts of money as plain data. A `Money` is `{ amount: "9.99", currency: "EUR" }`: JSON-safe, comparable field by field, and never computed in binary floating point (all arithmetic is on `bigint` scaled integers).
|
|
6
|
+
|
|
7
|
+
> Zero dependencies. It formats nothing; `@pyreon/format` displays a Money.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
bun add @pyreon/money
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Entries: `@pyreon/money`, `@pyreon/money/decimal` (exact decimal-string math), `@pyreon/money/fp` (value-last forms).
|
|
16
|
+
|
|
17
|
+
## Quick start
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { add, allocate, money, multiply, round } from '@pyreon/money'
|
|
21
|
+
|
|
22
|
+
add(money('0.10', 'EUR'), money('0.20', 'EUR')) // { amount: '0.30', currency: 'EUR' }
|
|
23
|
+
multiply(money('19.99', 'EUR'), 3) // { amount: '59.97', currency: 'EUR' }
|
|
24
|
+
allocate(money('100.00', 'EUR'), [1, 1, 1]).map((p) => p.amount) // ['33.34', '33.33', '33.33']
|
|
25
|
+
round(money('1.23', 'CHF'), { increment: '0.05' }) // { amount: '1.25', currency: 'CHF' }
|
|
26
|
+
|
|
27
|
+
money(0.1 + 0.2, 'EUR') // throws: that is floating-point noise, not an amount
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
| Area | Functions |
|
|
31
|
+
| --- | --- |
|
|
32
|
+
| Build and check | `money`, `fromMinor`, `toMinor`, `toMinorNumber`, `isMoney`, `zero` |
|
|
33
|
+
| Arithmetic | `add`, `subtract`, `negate`, `abs`, `sum`, `multiply`, `divide`, `percentage`, `ratio` |
|
|
34
|
+
| Sharing | `allocate`, `split` |
|
|
35
|
+
| Compare | `compare`, `equals`, `min`, `max`, `isZero`, `isPositive`, `isNegative` |
|
|
36
|
+
| Rounding and conversion | `round` (nine `Intl` modes, cash-rounding increments), `convert` |
|
|
37
|
+
| Currencies | `currencyDigits`, `isCurrency`, `defineCurrency` |
|
|
38
|
+
|
|
39
|
+
The default rounding mode is `halfExpand` (round half away from zero); `halfEven` is banker's rounding. Rounding is verified against `Intl.NumberFormat` for all nine modes, arithmetic against an independent rational reference, and `allocate` by property tests.
|
|
40
|
+
|
|
41
|
+
Full guide with recipes: [docs/money](https://pyreon.dev/docs/money).
|
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
import { a as pow10, c as wholeIn, d as show, i as formatScaled, l as badRange, n as checkMode, o as readDecimal, r as divRound, s as toScaled, t as MAX_DIGITS, u as badValue } from "./scaled-eXdrPpWS.js";
|
|
2
|
+
|
|
3
|
+
// src/currency.ts
|
|
4
|
+
/** The most currencies `defineCurrency` registers, and the most digit counts `currencyDigits` remembers. */
|
|
5
|
+
const LIMIT = 64;
|
|
6
|
+
const registry = /* @__PURE__ */ new Map();
|
|
7
|
+
const platform = /* @__PURE__ */ new Map();
|
|
8
|
+
let iso;
|
|
9
|
+
function isoCodes() {
|
|
10
|
+
if (iso === void 0) {
|
|
11
|
+
const list = Intl.supportedValuesOf?.("currency");
|
|
12
|
+
iso = list === void 0 ? null : new Set(list);
|
|
13
|
+
}
|
|
14
|
+
return iso;
|
|
15
|
+
}
|
|
16
|
+
function wellFormed(code) {
|
|
17
|
+
return code.length === 3 && code.charCodeAt(0) - 65 >>> 0 < 26 && code.charCodeAt(1) - 65 >>> 0 < 26 && code.charCodeAt(2) - 65 >>> 0 < 26;
|
|
18
|
+
}
|
|
19
|
+
/** The fraction digits `Intl` uses for an ISO code, remembered for `LIMIT` codes (the oldest is dropped first). */
|
|
20
|
+
function platformDigits(code) {
|
|
21
|
+
const hit = platform.get(code);
|
|
22
|
+
if (hit !== void 0) return hit;
|
|
23
|
+
if (!wellFormed(code)) return void 0;
|
|
24
|
+
const known = isoCodes();
|
|
25
|
+
if (known !== null && !known.has(code)) return void 0;
|
|
26
|
+
const digits = new Intl.NumberFormat("en", {
|
|
27
|
+
style: "currency",
|
|
28
|
+
currency: code
|
|
29
|
+
}).resolvedOptions().maximumFractionDigits ?? 2;
|
|
30
|
+
if (platform.size >= LIMIT) platform.delete(platform.keys().next().value);
|
|
31
|
+
platform.set(code, digits);
|
|
32
|
+
return digits;
|
|
33
|
+
}
|
|
34
|
+
/** The digits of a code for a calling function: a registered code, else the platform's, else a `[Pyreon]` error. */
|
|
35
|
+
function digitsOf(fn, code) {
|
|
36
|
+
return (typeof code === "string" ? registry.get(code) ?? platformDigits(code) : void 0) ?? unknownCurrency(fn, code);
|
|
37
|
+
}
|
|
38
|
+
function unknownCurrency(fn, code) {
|
|
39
|
+
const fix = typeof code === "string" && wellFormed(code.toUpperCase()) && code !== code.toUpperCase() ? `Currency codes are upper case: use ${JSON.stringify(code.toUpperCase())}.` : "Use an ISO 4217 code such as \"EUR\", or register your own with defineCurrency(\"PTS\", { digits: 0 }).";
|
|
40
|
+
return badValue(fn, "a known currency code", code, fix);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The number of minor-unit digits of a currency, from the platform (`Intl`; no currency table is shipped) or from
|
|
44
|
+
* `defineCurrency`: 2 for EUR, 0 for JPY, 3 for KWD.
|
|
45
|
+
*
|
|
46
|
+
* @example currencyDigits('EUR') // => 2
|
|
47
|
+
* @example currencyDigits('JPY') // => 0
|
|
48
|
+
* @example currencyDigits('KWD') // => 3
|
|
49
|
+
*/
|
|
50
|
+
function currencyDigits(code) {
|
|
51
|
+
return digitsOf("currencyDigits", code);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Whether `code` is a known currency: an upper-case ISO 4217 code the platform knows, or one registered with
|
|
55
|
+
* `defineCurrency`. Never throws.
|
|
56
|
+
*
|
|
57
|
+
* @example isCurrency('EUR') // => true
|
|
58
|
+
* @example isCurrency('eur') // => false
|
|
59
|
+
* @example isCurrency('XXXX') // => false
|
|
60
|
+
*/
|
|
61
|
+
function isCurrency(code) {
|
|
62
|
+
return typeof code === "string" && (registry.has(code) || platformDigits(code) !== void 0);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Register a currency the platform does not know (crypto, loyalty points, a test currency): `defineCurrency('PTS', { digits: 0 })`.
|
|
66
|
+
* The code is 2 to 12 upper-case letters or digits starting with a letter. Registering the same code again with the same
|
|
67
|
+
* digits is fine; with different digits it throws, as does changing an ISO currency's digits. The registry holds at most
|
|
68
|
+
* 64 currencies.
|
|
69
|
+
*
|
|
70
|
+
* @example defineCurrency('PTS', { digits: 0 }); currencyDigits('PTS') // => 0
|
|
71
|
+
*/
|
|
72
|
+
function defineCurrency(code, spec) {
|
|
73
|
+
if (!(typeof code === "string" && code.length >= 2 && code.length <= 12 && code.charCodeAt(0) - 65 >>> 0 < 26 && /^[A-Z][A-Z0-9]*$/.test(code))) return badValue("defineCurrency", "a code of 2 to 12 upper-case letters or digits starting with a letter", code, "Example: defineCurrency(\"PTS\", { digits: 0 }).");
|
|
74
|
+
const digits = spec?.digits;
|
|
75
|
+
if (typeof digits !== "number" || !Number.isInteger(digits) || digits < 0 || digits > 30) return badValue("defineCurrency", "spec.digits to be a whole number from 0 to 30", digits);
|
|
76
|
+
const existing = registry.get(code) ?? platformDigits(code);
|
|
77
|
+
if (existing !== void 0 && existing !== digits) return badRange("defineCurrency", `${code} is already defined with ${existing} digits and cannot be redefined with ${digits}. Pick another code for a different currency.`);
|
|
78
|
+
if (registry.has(code)) return;
|
|
79
|
+
if (registry.size >= LIMIT) return badRange("defineCurrency", `at most ${LIMIT} currencies can be registered, got ${show(code)} as number 65. This is a registry for a few custom currencies, not a table.`);
|
|
80
|
+
registry.set(code, digits);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/money.ts
|
|
84
|
+
const MONEY_HINT = "a Money such as { amount: \"9.99\", currency: \"EUR\" }";
|
|
85
|
+
/** The digits of a Money's currency, after checking it is shaped like one. */
|
|
86
|
+
function digitsOfMoney(fn, m) {
|
|
87
|
+
if (typeof m !== "object" || m === null || typeof m.amount !== "string" || typeof m.currency !== "string") return badValue(fn, MONEY_HINT, m, "Check data with isMoney() before using it.");
|
|
88
|
+
return digitsOf(fn, m.currency);
|
|
89
|
+
}
|
|
90
|
+
function notCanonical(fn, m, digits) {
|
|
91
|
+
return badValue(fn, `an amount written with exactly ${digits} fraction digit${digits === 1 ? "" : "s"} for ${m.currency}`, m.amount, "Build a Money with money(), fromMinor() or zero(), and check data with isMoney().");
|
|
92
|
+
}
|
|
93
|
+
/** The minor units of an amount: a `number` when it has at most 15 digits, else a `bigint`. Validates the canonical shape. */
|
|
94
|
+
/** The cheap checks of a canonical amount: length, a dot where the digits say, an integer part without a leading zero. */
|
|
95
|
+
function shapeOk(text, start, dot, digits) {
|
|
96
|
+
const intEnd = digits > 0 ? dot : text.length;
|
|
97
|
+
if (text.length > 4096 + 2 || intEnd - start < 1) return false;
|
|
98
|
+
if (digits > 0 && text.charCodeAt(dot) !== 46) return false;
|
|
99
|
+
return intEnd - start === 1 || text.charCodeAt(start) !== 48;
|
|
100
|
+
}
|
|
101
|
+
function readMinor(fn, m, digits) {
|
|
102
|
+
const text = m.amount;
|
|
103
|
+
const len = text.length;
|
|
104
|
+
const neg = len > 0 && text.charCodeAt(0) === 45;
|
|
105
|
+
const start = neg ? 1 : 0;
|
|
106
|
+
const dot = digits > 0 ? len - digits - 1 : -1;
|
|
107
|
+
if (!shapeOk(text, start, dot, digits)) return notCanonical(fn, m, digits);
|
|
108
|
+
let n = 0;
|
|
109
|
+
let nonzero = false;
|
|
110
|
+
for (let i = start; i < len; i++) {
|
|
111
|
+
if (i === dot) continue;
|
|
112
|
+
const d = text.charCodeAt(i) - 48;
|
|
113
|
+
if (d >>> 0 > 9) return notCanonical(fn, m, digits);
|
|
114
|
+
n = n * 10 + d;
|
|
115
|
+
if (d !== 0) nonzero = true;
|
|
116
|
+
}
|
|
117
|
+
if (neg && !nonzero) return notCanonical(fn, m, digits);
|
|
118
|
+
if (len - start - (digits > 0 ? 1 : 0) <= 15) return neg ? -n : n;
|
|
119
|
+
const big = BigInt(digits > 0 ? text.slice(start, dot) + text.slice(dot + 1) : text.slice(start));
|
|
120
|
+
return neg ? -big : big;
|
|
121
|
+
}
|
|
122
|
+
/** An amount's minor units as a bigint, for the paths that need one. */
|
|
123
|
+
function minorBig(fn, m, digits) {
|
|
124
|
+
const v = readMinor(fn, m, digits);
|
|
125
|
+
return typeof v === "bigint" ? v : BigInt(v);
|
|
126
|
+
}
|
|
127
|
+
function writeMinor(minor, digits) {
|
|
128
|
+
const neg = minor < 0;
|
|
129
|
+
let text = String(neg ? -minor : minor);
|
|
130
|
+
if (digits > 0) {
|
|
131
|
+
if (text.length <= digits) text = "0".repeat(digits - text.length + 1) + text;
|
|
132
|
+
text = `${text.slice(0, text.length - digits)}.${text.slice(text.length - digits)}`;
|
|
133
|
+
}
|
|
134
|
+
return neg ? `-${text}` : text;
|
|
135
|
+
}
|
|
136
|
+
function make(minor, currency, digits) {
|
|
137
|
+
return {
|
|
138
|
+
amount: writeMinor(minor, digits),
|
|
139
|
+
currency
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function mixed(fn, a, b) {
|
|
143
|
+
return badRange(fn, `cannot combine ${a.currency} with ${b.currency}: a Money has one currency. Convert one side first with convert(money, "${a.currency}", rate).`);
|
|
144
|
+
}
|
|
145
|
+
/** Check both are Money of one currency and return its digits. */
|
|
146
|
+
function pair(fn, a, b) {
|
|
147
|
+
const digits = digitsOfMoney(fn, a);
|
|
148
|
+
digitsOfMoney(fn, b);
|
|
149
|
+
if (a.currency !== b.currency) return mixed(fn, a, b);
|
|
150
|
+
return digits;
|
|
151
|
+
}
|
|
152
|
+
function toMinorScaled(fn, value, ctx) {
|
|
153
|
+
const { currency, digits, mode, original } = ctx;
|
|
154
|
+
if (value.s <= digits) return value.n * pow10(digits - value.s);
|
|
155
|
+
const unit = pow10(value.s - digits);
|
|
156
|
+
if (value.n % unit === 0n) return value.n / unit;
|
|
157
|
+
if (mode !== void 0) return divRound(value.n, unit, mode);
|
|
158
|
+
const why = typeof original === "number" ? `${String(original)} has more decimals than ${currency} has (${digits}): that is floating-point noise (0.1 + 0.2 is 0.30000000000000004 in binary floating point), not an amount.` : `${JSON.stringify(original)} has more decimals than ${currency} has (${digits}), so it would lose value.`;
|
|
159
|
+
return badRange(fn, `${why} Round it deliberately: money(x, "${currency}", { rounding: "halfExpand" }). Better, keep amounts as decimal strings or minor units.`);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Build a Money. A string is exact; a number is read by its shortest round-trip text (`9.99` is exactly 9.99, not the binary
|
|
163
|
+
* float near it); a bigint is whole units. A value with more decimals than the currency has throws unless `rounding` is given
|
|
164
|
+
* (so `money(0.1 + 0.2, 'EUR')` throws and explains floating point, instead of hiding the bug). The amount of the result has
|
|
165
|
+
* exactly the currency's digits: `"9.90"`, `"100"` for JPY, `"0.123"` for KWD.
|
|
166
|
+
*
|
|
167
|
+
* @example money(9.99, 'EUR') // => { amount: '9.99', currency: 'EUR' }
|
|
168
|
+
* @example money('10', 'EUR') // => { amount: '10.00', currency: 'EUR' }
|
|
169
|
+
* @example money(100, 'JPY') // => { amount: '100', currency: 'JPY' }
|
|
170
|
+
* @example money(0.1 + 0.2, 'EUR', { rounding: 'halfExpand' }) // => { amount: '0.30', currency: 'EUR' }
|
|
171
|
+
*/
|
|
172
|
+
function money(amount, currency, options) {
|
|
173
|
+
const digits = digitsOf("money", currency);
|
|
174
|
+
const mode = options?.rounding === void 0 ? void 0 : checkMode("money", options.rounding);
|
|
175
|
+
const value = toScaled("money", "amount", amount);
|
|
176
|
+
return {
|
|
177
|
+
amount: formatScaled(toMinorScaled("money", value, {
|
|
178
|
+
currency,
|
|
179
|
+
digits,
|
|
180
|
+
mode,
|
|
181
|
+
original: amount
|
|
182
|
+
}), digits),
|
|
183
|
+
currency
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* A Money from minor units (cents): `fromMinor(999, 'EUR')` is 9.99. A number must be a safe integer; use a bigint or a
|
|
188
|
+
* digit string above 2^53.
|
|
189
|
+
*
|
|
190
|
+
* @example fromMinor(999, 'EUR') // => { amount: '9.99', currency: 'EUR' }
|
|
191
|
+
* @example fromMinor('123456789012345678901', 'EUR') // => { amount: '1234567890123456789.01', currency: 'EUR' }
|
|
192
|
+
*/
|
|
193
|
+
function fromMinor(units, currency) {
|
|
194
|
+
const digits = digitsOf("fromMinor", currency);
|
|
195
|
+
let n;
|
|
196
|
+
if (typeof units === "bigint") n = units;
|
|
197
|
+
else if (typeof units === "number") {
|
|
198
|
+
if (!Number.isSafeInteger(units)) return badValue("fromMinor", "a safe integer number of minor units", units, "Above 2^53 a number is not exact: pass a bigint or a string of digits.");
|
|
199
|
+
n = BigInt(units);
|
|
200
|
+
} else {
|
|
201
|
+
const parsed = typeof units === "string" ? readDecimal("fromMinor", units, true) : null;
|
|
202
|
+
if (parsed === null || parsed.s !== 0) return badValue("fromMinor", "minor units as a whole number", units);
|
|
203
|
+
n = parsed.n;
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
amount: formatScaled(n, digits),
|
|
207
|
+
currency
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* The amount in minor units as a bigint: `toMinor(money('9.99', 'EUR'))` is `999n`.
|
|
212
|
+
*
|
|
213
|
+
* @example toMinor(money('9.99', 'EUR')) // => 999n
|
|
214
|
+
*/
|
|
215
|
+
function toMinor(m) {
|
|
216
|
+
return minorBig("toMinor", m, digitsOfMoney("toMinor", m));
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The amount in minor units as a number; throws beyond the safe integer range, where a number would not be exact.
|
|
220
|
+
*
|
|
221
|
+
* @example toMinorNumber(money('9.99', 'EUR')) // => 999
|
|
222
|
+
*/
|
|
223
|
+
function toMinorNumber(m) {
|
|
224
|
+
const v = readMinor("toMinorNumber", m, digitsOfMoney("toMinorNumber", m));
|
|
225
|
+
if (typeof v === "number") return v;
|
|
226
|
+
return v >= -9007199254740991n && v <= 9007199254740991n ? Number(v) : badRange("toMinorNumber", `${m.amount} ${m.currency} is ${v} minor units, beyond the safe integer range of a number. Use toMinor(), which returns a bigint.`);
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Whether `x` is a Money: exactly the fields `amount` and `currency`, a known currency, and a canonical amount with exactly
|
|
230
|
+
* that currency's digits. Never throws.
|
|
231
|
+
*
|
|
232
|
+
* @example isMoney({ amount: '9.99', currency: 'EUR' }) // => true
|
|
233
|
+
* @example isMoney({ amount: '9.9', currency: 'EUR' }) // => false
|
|
234
|
+
* @example isMoney({ amount: 9.99, currency: 'EUR' }) // => false
|
|
235
|
+
*/
|
|
236
|
+
function isMoney(x) {
|
|
237
|
+
try {
|
|
238
|
+
if (typeof x !== "object" || x === null || Object.keys(x).length !== 2) return false;
|
|
239
|
+
const m = x;
|
|
240
|
+
if (typeof m.amount !== "string" || typeof m.currency !== "string") return false;
|
|
241
|
+
readMinor("isMoney", m, digitsOf("isMoney", m.currency));
|
|
242
|
+
return true;
|
|
243
|
+
} catch {
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Zero in a currency.
|
|
249
|
+
*
|
|
250
|
+
* @example zero('EUR') // => { amount: '0.00', currency: 'EUR' }
|
|
251
|
+
*/
|
|
252
|
+
function zero(currency) {
|
|
253
|
+
return {
|
|
254
|
+
amount: writeMinor(0, digitsOf("zero", currency)),
|
|
255
|
+
currency
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
function combine(fn, a, b, sign) {
|
|
259
|
+
const digits = pair(fn, a, b);
|
|
260
|
+
const x = readMinor(fn, a, digits);
|
|
261
|
+
const y = readMinor(fn, b, digits);
|
|
262
|
+
if (typeof x === "number" && typeof y === "number") {
|
|
263
|
+
const r = sign === 1 ? x + y : x - y;
|
|
264
|
+
if (Number.isSafeInteger(r)) return make(r, a.currency, digits);
|
|
265
|
+
}
|
|
266
|
+
const bx = typeof x === "bigint" ? x : BigInt(x);
|
|
267
|
+
const by = typeof y === "bigint" ? y : BigInt(y);
|
|
268
|
+
return make(sign === 1 ? bx + by : bx - by, a.currency, digits);
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Exact sum of two amounts of one currency. Mixing currencies throws and names both.
|
|
272
|
+
*
|
|
273
|
+
* @example add(money('0.10', 'EUR'), money('0.20', 'EUR')) // => { amount: '0.30', currency: 'EUR' }
|
|
274
|
+
*/
|
|
275
|
+
function add(a, b) {
|
|
276
|
+
return combine("add", a, b, 1);
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Exact difference `a - b` of two amounts of one currency.
|
|
280
|
+
*
|
|
281
|
+
* @example subtract(money('1.00', 'EUR'), money('0.01', 'EUR')) // => { amount: '0.99', currency: 'EUR' }
|
|
282
|
+
*/
|
|
283
|
+
function subtract(a, b) {
|
|
284
|
+
return combine("subtract", a, b, -1);
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* The same amount with the opposite sign.
|
|
288
|
+
*
|
|
289
|
+
* @example negate(money('5', 'EUR')) // => { amount: '-5.00', currency: 'EUR' }
|
|
290
|
+
*/
|
|
291
|
+
function negate(m) {
|
|
292
|
+
const digits = digitsOfMoney("negate", m);
|
|
293
|
+
const v = readMinor("negate", m, digits);
|
|
294
|
+
return make(typeof v === "number" ? -v + 0 : -v, m.currency, digits);
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* The amount without its sign.
|
|
298
|
+
*
|
|
299
|
+
* @example abs(money('-5', 'EUR')) // => { amount: '5.00', currency: 'EUR' }
|
|
300
|
+
*/
|
|
301
|
+
function abs(m) {
|
|
302
|
+
const digits = digitsOfMoney("abs", m);
|
|
303
|
+
const v = readMinor("abs", m, digits);
|
|
304
|
+
return make(v < 0 ? -v : v, m.currency, digits);
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* The sum of a list of one currency. An empty list needs `currency`.
|
|
308
|
+
*
|
|
309
|
+
* @example sum([money('1.10', 'EUR'), money('2.20', 'EUR')]) // => { amount: '3.30', currency: 'EUR' }
|
|
310
|
+
* @example sum([], 'EUR') // => { amount: '0.00', currency: 'EUR' }
|
|
311
|
+
*/
|
|
312
|
+
function sum(list, currency) {
|
|
313
|
+
if (list === null || list === void 0 || typeof list[Symbol.iterator] !== "function") return badValue("sum", "a list of Money", list);
|
|
314
|
+
let code = currency;
|
|
315
|
+
let digits = code === void 0 ? -1 : digitsOf("sum", code);
|
|
316
|
+
let total = 0n;
|
|
317
|
+
for (const m of list) {
|
|
318
|
+
if (code === void 0) {
|
|
319
|
+
digits = digitsOfMoney("sum", m);
|
|
320
|
+
code = m.currency;
|
|
321
|
+
} else if (digitsOfMoney("sum", m) !== digits || m.currency !== code) return badRange("sum", `cannot sum ${code} with ${m.currency}: a list of Money must be one currency. Convert first with convert().`);
|
|
322
|
+
total += minorBig("sum", m, digits);
|
|
323
|
+
}
|
|
324
|
+
return code === void 0 ? badRange("sum", "an empty list has no currency. Pass it: sum([], \"EUR\").") : make(total, code, digits);
|
|
325
|
+
}
|
|
326
|
+
function rounding(fn, options) {
|
|
327
|
+
return options?.rounding === void 0 ? "halfExpand" : checkMode(fn, options.rounding);
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* The amount times a plain number, rounded to the currency's digits (default `'halfExpand'`). The factor is a pure number: a
|
|
331
|
+
* number is read by its shortest text, so `1.21` is exactly 1.21; prefer a string. For a Money times a Money there is no
|
|
332
|
+
* operation, because it has no meaning.
|
|
333
|
+
*
|
|
334
|
+
* @example multiply(money('19.99', 'EUR'), 3) // => { amount: '59.97', currency: 'EUR' }
|
|
335
|
+
* @example multiply(money('10.00', 'EUR'), '1.21') // => { amount: '12.10', currency: 'EUR' }
|
|
336
|
+
* @example multiply(money('0.05', 'EUR'), '0.5') // => { amount: '0.03', currency: 'EUR' }
|
|
337
|
+
*/
|
|
338
|
+
function multiply(m, factor, options) {
|
|
339
|
+
const digits = digitsOfMoney("multiply", m);
|
|
340
|
+
const f = toScaled("multiply", "factor", factor);
|
|
341
|
+
const mode = rounding("multiply", options);
|
|
342
|
+
return make(divRound(minorBig("multiply", m, digits) * f.n, pow10(f.s), mode), m.currency, digits);
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* The amount divided by a plain number, rounded to the currency's digits. A zero divisor throws. To split an amount without
|
|
346
|
+
* losing a cent use `allocate` or `split`: dividing three ways and multiplying back does not give the amount.
|
|
347
|
+
*
|
|
348
|
+
* @example divide(money('10.00', 'EUR'), 3) // => { amount: '3.33', currency: 'EUR' }
|
|
349
|
+
*/
|
|
350
|
+
function divide(m, divisor, options) {
|
|
351
|
+
const digits = digitsOfMoney("divide", m);
|
|
352
|
+
const d = toScaled("divide", "divisor", divisor);
|
|
353
|
+
const mode = rounding("divide", options);
|
|
354
|
+
if (d.n === 0n) return badRange("divide", `the divisor ${JSON.stringify(String(divisor))} is zero`);
|
|
355
|
+
return make(divRound(minorBig("divide", m, digits) * pow10(d.s), d.n, mode), m.currency, digits);
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* `percent` percent of an amount, rounded to the currency's digits.
|
|
359
|
+
*
|
|
360
|
+
* @example percentage(money('200.00', 'EUR'), 21) // => { amount: '42.00', currency: 'EUR' }
|
|
361
|
+
* @example percentage(money('9.99', 'EUR'), '7.5') // => { amount: '0.75', currency: 'EUR' }
|
|
362
|
+
*/
|
|
363
|
+
function percentage(m, percent, options) {
|
|
364
|
+
const digits = digitsOfMoney("percentage", m);
|
|
365
|
+
const p = toScaled("percentage", "percent", percent);
|
|
366
|
+
const mode = rounding("percentage", options);
|
|
367
|
+
return make(divRound(minorBig("percentage", m, digits) * p.n, pow10(p.s) * 100n, mode), m.currency, digits);
|
|
368
|
+
}
|
|
369
|
+
function ratiosOf(fn, ratios) {
|
|
370
|
+
if (!Array.isArray(ratios) || ratios.length === 0 || ratios.length > 1e5) return badValue(fn, "a non-empty array of ratios such as [1, 1, 2] or [\"0.5\", \"0.5\"]", ratios);
|
|
371
|
+
const parsed = ratios.map((r) => toScaled(fn, "every ratio", r));
|
|
372
|
+
const scale = parsed.reduce((s, r) => r.s > s ? r.s : s, 0);
|
|
373
|
+
const ints = parsed.map((r) => r.n * pow10(scale - r.s));
|
|
374
|
+
if (ints.some((n) => n < 0n)) return badRange(fn, `ratios must not be negative, got ${JSON.stringify(ratios.map(String))}`);
|
|
375
|
+
if (ints.every((n) => n === 0n)) return badRange(fn, `the ratios are all zero (${JSON.stringify(ratios.map(String))}), so there is nothing to share by. Give at least one ratio above zero.`);
|
|
376
|
+
return ints;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Share an amount by ratios so that the parts sum EXACTLY to the amount. Each part is its floor share in minor units; the
|
|
380
|
+
* minor units left over go one each to the parts with the largest fractional remainders, ties to the first. A negative amount
|
|
381
|
+
* is shared by its absolute value and the parts take its sign. A ratio of zero gets zero. All-zero or negative ratios throw.
|
|
382
|
+
* Each part is within one minor unit of its exact share. Reordering the ratios reorders the parts, but a tie can move a cent.
|
|
383
|
+
*
|
|
384
|
+
* @example allocate(money('100.00', 'EUR'), [1, 1, 1]).map((p) => p.amount) // => ['33.34', '33.33', '33.33']
|
|
385
|
+
* @example allocate(money('0.05', 'EUR'), [3, 7]).map((p) => p.amount) // => ['0.02', '0.03']
|
|
386
|
+
* @example allocate(money('10.00', 'EUR'), [0, 1]).map((p) => p.amount) // => ['0.00', '10.00']
|
|
387
|
+
*/
|
|
388
|
+
function allocate(m, ratios) {
|
|
389
|
+
const digits = digitsOfMoney("allocate", m);
|
|
390
|
+
const weights = ratiosOf("allocate", ratios);
|
|
391
|
+
const minor = minorBig("allocate", m, digits);
|
|
392
|
+
const negative = minor < 0n;
|
|
393
|
+
const total = negative ? -minor : minor;
|
|
394
|
+
let weightSum = 0n;
|
|
395
|
+
for (const w of weights) weightSum += w;
|
|
396
|
+
const floors = [];
|
|
397
|
+
const rests = [];
|
|
398
|
+
let given = 0n;
|
|
399
|
+
for (const w of weights) {
|
|
400
|
+
const product = total * w;
|
|
401
|
+
floors.push(product / weightSum);
|
|
402
|
+
rests.push(product % weightSum);
|
|
403
|
+
given += product / weightSum;
|
|
404
|
+
}
|
|
405
|
+
const order = weights.map((_, i) => i).sort((i, j) => rests[i] === rests[j] ? i - j : rests[i] > rests[j] ? -1 : 1);
|
|
406
|
+
for (let k = 0n; k < total - given; k++) floors[order[Number(k)]] += 1n;
|
|
407
|
+
return floors.map((part) => make(negative ? -part : part, m.currency, digits));
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Split an amount into `parts` equal parts that sum exactly to it: the first parts get the extra cent.
|
|
411
|
+
*
|
|
412
|
+
* @example split(money('100.00', 'EUR'), 3).map((p) => p.amount) // => ['33.34', '33.33', '33.33']
|
|
413
|
+
*/
|
|
414
|
+
function split(m, parts) {
|
|
415
|
+
const n = wholeIn("split", "parts", parts, 1, 1e5);
|
|
416
|
+
return allocate(m, new Array(n).fill(1));
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* `a / b` as a decimal string with trailing zeros removed, rounded to `scale` digits (default 10). Both amounts must be one
|
|
420
|
+
* currency; a zero `b` throws.
|
|
421
|
+
*
|
|
422
|
+
* @example ratio(money('1.00', 'EUR'), money('4.00', 'EUR')) // => '0.25'
|
|
423
|
+
* @example ratio(money('1.00', 'EUR'), money('3.00', 'EUR'), { scale: 4 }) // => '0.3333'
|
|
424
|
+
*/
|
|
425
|
+
function ratio(a, b, options) {
|
|
426
|
+
const digits = pair("ratio", a, b);
|
|
427
|
+
const scale = options?.scale === void 0 ? 10 : wholeIn("ratio", "scale", options.scale, 0, 1e3);
|
|
428
|
+
const mode = options?.rounding === void 0 ? "halfExpand" : checkMode("ratio", options.rounding);
|
|
429
|
+
const y = minorBig("ratio", b, digits);
|
|
430
|
+
if (y === 0n) return badRange("ratio", `the second amount is zero (${b.amount} ${b.currency}), so the ratio is undefined`);
|
|
431
|
+
const text = formatScaled(divRound(minorBig("ratio", a, digits) * pow10(scale), y, mode), scale);
|
|
432
|
+
return scale === 0 || !text.includes(".") ? text : text.replace(/0+$/, "").replace(/\.$/, "");
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* -1, 0 or 1. Different currencies throw (they cannot be ordered without a rate).
|
|
436
|
+
*
|
|
437
|
+
* @example compare(money('1.00', 'EUR'), money('2.00', 'EUR')) // => -1
|
|
438
|
+
*/
|
|
439
|
+
function compare(a, b) {
|
|
440
|
+
const digits = pair("compare", a, b);
|
|
441
|
+
const x = readMinor("compare", a, digits);
|
|
442
|
+
const y = readMinor("compare", b, digits);
|
|
443
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Whether two amounts are equal. Amounts of different currencies are not equal (this does not throw).
|
|
447
|
+
*
|
|
448
|
+
* @example equals(money('1.5', 'EUR'), money('1.50', 'EUR')) // => true
|
|
449
|
+
* @example equals(money('1', 'EUR'), money('1', 'USD')) // => false
|
|
450
|
+
*/
|
|
451
|
+
function equals(a, b) {
|
|
452
|
+
const digits = digitsOfMoney("equals", a);
|
|
453
|
+
const other = digitsOfMoney("equals", b);
|
|
454
|
+
if (a.currency !== b.currency) return false;
|
|
455
|
+
readMinor("equals", a, digits);
|
|
456
|
+
readMinor("equals", b, other);
|
|
457
|
+
return a.amount === b.amount;
|
|
458
|
+
}
|
|
459
|
+
function extreme(fn, list, sign) {
|
|
460
|
+
if (list.length === 0) return badRange(fn, "needs at least one amount");
|
|
461
|
+
let best = list[0];
|
|
462
|
+
digitsOfMoney(fn, best);
|
|
463
|
+
for (let i = 1; i < list.length; i++) if (compare(list[i], best) === sign) best = list[i];
|
|
464
|
+
return best;
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* The smallest amount. At least one is required; currencies must match.
|
|
468
|
+
*
|
|
469
|
+
* @example min(money('3', 'EUR'), money('2', 'EUR')) // => { amount: '2.00', currency: 'EUR' }
|
|
470
|
+
*/
|
|
471
|
+
function min(...amounts) {
|
|
472
|
+
return extreme("min", amounts, -1);
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* The largest amount. At least one is required; currencies must match.
|
|
476
|
+
*
|
|
477
|
+
* @example max(money('3', 'EUR'), money('2', 'EUR')) // => { amount: '3.00', currency: 'EUR' }
|
|
478
|
+
*/
|
|
479
|
+
function max(...amounts) {
|
|
480
|
+
return extreme("max", amounts, 1);
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Whether the amount is zero.
|
|
484
|
+
*
|
|
485
|
+
* @example isZero(zero('EUR')) // => true
|
|
486
|
+
*/
|
|
487
|
+
function isZero(m) {
|
|
488
|
+
return readMinor("isZero", m, digitsOfMoney("isZero", m)) == 0;
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Whether the amount is above zero.
|
|
492
|
+
*
|
|
493
|
+
* @example isPositive(money('0.01', 'EUR')) // => true
|
|
494
|
+
*/
|
|
495
|
+
function isPositive(m) {
|
|
496
|
+
return readMinor("isPositive", m, digitsOfMoney("isPositive", m)) > 0;
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Whether the amount is below zero.
|
|
500
|
+
*
|
|
501
|
+
* @example isNegative(money('-0.01', 'EUR')) // => true
|
|
502
|
+
*/
|
|
503
|
+
function isNegative(m) {
|
|
504
|
+
return readMinor("isNegative", m, digitsOfMoney("isNegative", m)) < 0;
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Round to fewer digits or to a multiple of an increment (cash rounding), by `mode` (default `'halfExpand'`, round half away
|
|
508
|
+
* from zero; `'halfEven'` is banker's rounding). With no options it is the amount itself, because a Money always has exactly
|
|
509
|
+
* its currency's digits.
|
|
510
|
+
*
|
|
511
|
+
* @example round(money('12.34', 'EUR'), { digits: 0 }) // => { amount: '12.00', currency: 'EUR' }
|
|
512
|
+
* @example round(money('1.23', 'CHF'), { increment: '0.05' }) // => { amount: '1.25', currency: 'CHF' }
|
|
513
|
+
* @example round(money('2.50', 'EUR'), { digits: 0, mode: 'halfEven' }) // => { amount: '2.00', currency: 'EUR' }
|
|
514
|
+
*/
|
|
515
|
+
function round(m, options) {
|
|
516
|
+
const digits = digitsOfMoney("round", m);
|
|
517
|
+
const mode = options?.mode === void 0 ? "halfExpand" : checkMode("round", options.mode);
|
|
518
|
+
const minor = minorBig("round", m, digits);
|
|
519
|
+
if (options?.increment !== void 0 && options.digits !== void 0) return badValue("round", "either digits or increment", options, "Pass one: digits to keep fewer digits, increment for cash rounding.");
|
|
520
|
+
let unit = 1n;
|
|
521
|
+
if (options?.increment !== void 0) {
|
|
522
|
+
const inc = toScaled("round", "increment", options.increment);
|
|
523
|
+
const scaled = inc.n * pow10(digits);
|
|
524
|
+
if (inc.n <= 0n) return badRange("round", `increment must be greater than zero, got ${JSON.stringify(String(options.increment))}`);
|
|
525
|
+
if (scaled % pow10(inc.s) !== 0n) return badRange("round", `the increment ${JSON.stringify(String(options.increment))} is smaller than a ${m.currency} minor unit (${digits} digits)`);
|
|
526
|
+
unit = scaled / pow10(inc.s);
|
|
527
|
+
} else if (options?.digits !== void 0) {
|
|
528
|
+
const keep = wholeIn("round", "digits", options.digits, 0, 1e3);
|
|
529
|
+
if (keep < digits) unit = pow10(digits - keep);
|
|
530
|
+
}
|
|
531
|
+
return make(divRound(minor, unit, mode) * unit, m.currency, digits);
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Convert to another currency with a rate (`1 unit of m.currency = rate units of to`), rounded to the target's digits. Give
|
|
535
|
+
* the rate as a decimal string; a number is read by its shortest text. Keep `{ from, to, rate }` next to the result: it is the
|
|
536
|
+
* audit trail.
|
|
537
|
+
*
|
|
538
|
+
* @example convert(money('100.00', 'EUR'), 'USD', '1.0842') // => { amount: '108.42', currency: 'USD' }
|
|
539
|
+
* @example convert(money('100.00', 'EUR'), 'JPY', '162.5') // => { amount: '16250', currency: 'JPY' }
|
|
540
|
+
*/
|
|
541
|
+
function convert(m, to, rate, options) {
|
|
542
|
+
const from = digitsOfMoney("convert", m);
|
|
543
|
+
const target = digitsOf("convert", to);
|
|
544
|
+
const r = toScaled("convert", "rate", rate);
|
|
545
|
+
const mode = rounding("convert", options);
|
|
546
|
+
if (r.n <= 0n) return badRange("convert", `the rate must be greater than zero, got ${JSON.stringify(String(rate))}`);
|
|
547
|
+
return make(divRound(minorBig("convert", m, from) * r.n * pow10(target), pow10(from + r.s), mode), to, target);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
export { sum as C, currencyDigits as D, zero as E, defineCurrency as O, subtract as S, toMinorNumber as T, negate as _, convert as a, round as b, fromMinor as c, isPositive as d, isZero as f, multiply as g, money as h, compare as i, isCurrency as k, isMoney as l, min as m, add as n, divide as o, max as p, allocate as r, equals as s, abs as t, isNegative as u, percentage as v, toMinor as w, split as x, ratio as y };
|
|
551
|
+
//# sourceMappingURL=money-B9MhDL2i.js.map
|