@newnormal/money 0.0.0-stage → 0.1.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 +86 -2
- package/dist/currencies.d.ts +14 -0
- package/dist/currencies.js +29 -0
- package/dist/decimal.d.ts +46 -0
- package/dist/decimal.js +87 -0
- package/dist/fx.d.ts +36 -0
- package/dist/fx.js +86 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +11 -0
- package/dist/money.d.ts +114 -0
- package/dist/money.js +276 -0
- package/dist/price.d.ts +36 -0
- package/dist/price.js +81 -0
- package/dist/rate.d.ts +59 -0
- package/dist/rate.js +129 -0
- package/dist/tax.d.ts +32 -0
- package/dist/tax.js +34 -0
- package/package.json +52 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 newnormal-commerce
|
|
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,87 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @newnormal/money
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
One money format: `"NOK 499.00"`. An ISO 4217 code, one space, the amount with exactly the
|
|
4
|
+
currency's decimals. Exact maths on bigint, rounding only where you say so, never a float.
|
|
5
|
+
Zero dependencies; runs on Bun, Node, Deno and edge runtimes.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { convert, DEFAULT_ROUNDING, FxRate, Money, Price, Rate } from '@newnormal/money';
|
|
9
|
+
|
|
10
|
+
const price = Money.parse('NOK 499'); // NOK 499.00
|
|
11
|
+
price.toString(); // "NOK 499.00"
|
|
12
|
+
price.toObject(); // { currency: "NOK", value: "499.00", minor: 49900 }
|
|
13
|
+
Money.parse('JPY 1200').minor; // 1200n (JPY has no decimals)
|
|
14
|
+
Money.parse('ISK 4990.00'); // ISK 4990 (extra zeros are fine)
|
|
15
|
+
Money.parse('NOK 4.999'); // throws too_many_decimals: never rounded
|
|
16
|
+
|
|
17
|
+
price.add(Money.parse('NOK 1')); // NOK 500.00
|
|
18
|
+
price.add(Money.parse('SEK 1')); // throws currency_mismatch
|
|
19
|
+
Money.parse('EUR 1').equals(Money.parse('NOK 1')); // false
|
|
20
|
+
|
|
21
|
+
Money.parse('NOK 100').allocate([1, 1, 1]); // NOK 33.34, NOK 33.33, NOK 33.33
|
|
22
|
+
price.multiply(Rate.percent('25'), 'half-up'); // NOK 124.75
|
|
23
|
+
convert(Money.parse('EUR 10'), FxRate.parse('EUR/NOK 11.7352'), DEFAULT_ROUNDING); // NOK 117.35
|
|
24
|
+
Price.parse('NOK 0.0035').times(1000, 'half-up'); // NOK 3.50
|
|
25
|
+
price.format('nb-NO'); // "499,00 kr"
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## The rules
|
|
29
|
+
|
|
30
|
+
1. Canonical Money is `"<ISO 4217 code> <decimal>"`: `"NOK 499.00"`, `"ISK 4990"`, `"JPY 1200"`,
|
|
31
|
+
`"KWD 1.250"`, `"NOK -3.81"`. No thousands separators, `.` as the decimal mark, exactly the
|
|
32
|
+
currency's decimals on output, the minus sign right before the digits.
|
|
33
|
+
2. Input may have fewer decimals (`"NOK 499"` is `"NOK 499.00"`), and extra decimals that are all
|
|
34
|
+
zero (`"ISK 4990.00"` is `"ISK 4990"`). A non-zero digit past the currency's decimals is an
|
|
35
|
+
error (`"NOK 4.999"`), never rounded. An unknown currency is an error.
|
|
36
|
+
3. One versioned ISO 4217 exponent table (`ISO_4217_VERSION`, from the SIX list of that date):
|
|
37
|
+
exponents 0, 2, 3 and 4.
|
|
38
|
+
4. Maths is exact: bigint minor units, products and quotients as exact fractions, rounded once
|
|
39
|
+
where the result becomes Money, with a named mode: `half-up` (half away from zero, the default
|
|
40
|
+
for customer-facing amounts, `DEFAULT_ROUNDING`), `half-even`, `down` (toward zero) or `up`.
|
|
41
|
+
5. Amounts in different currencies are never added or compared (`compare`, `add`, `subtract`
|
|
42
|
+
throw; `equals` is false). Conversion takes an `FxRate` for a currency pair
|
|
43
|
+
(`"EUR/NOK 11.7352"`) and a rounding mode, and checks the pair.
|
|
44
|
+
6. A `Rate` is dimensionless, kept as an exact factor; the constructor says the unit:
|
|
45
|
+
`Rate.percent("25")` is `Rate.factor("0.25")`. A `Price` is a unit price with a currency and up
|
|
46
|
+
to 10 decimals (`"NOK 0.0035"`); prices add within a currency, never to Money, and become Money
|
|
47
|
+
in one place, `price.times(quantity, mode)`. Wire fields say their unit: `taxRate` is a percent.
|
|
48
|
+
7. The object form, for systems that want integers: `{ currency, value, minor }`. `minor` is a JSON
|
|
49
|
+
integer up to 2^53 − 1; past that `toObject()` throws `amount_too_large`, never rounds.
|
|
50
|
+
|
|
51
|
+
## API
|
|
52
|
+
|
|
53
|
+
- `Money.parse(s)`, `Money.tryParse(s)`, `Money.isMoney(s)`, `Money.of(currency, "499.5" | 49950n)`,
|
|
54
|
+
`Money.fromMinor(currency, n)`, `Money.fromObject(o)`, `Money.zero(c)`, `Money.sum(list, c?)`
|
|
55
|
+
- `m.currency`, `m.minor` (bigint), `m.minorNumber` (throws past 2^53), `m.value`, `m.exponent`,
|
|
56
|
+
`toString()`, `toJSON()`, `toObject()`, `format(locale, options?)`
|
|
57
|
+
- `add`, `subtract`, `negate`, `abs`, `isZero`, `isNegative`, `isPositive`, `compare`,
|
|
58
|
+
`greaterThan`, `lessThan` (throw across currencies), `equals`, `sameCurrency`
|
|
59
|
+
- `multiply(rate | integer, mode)`, `divide(rate | integer, mode)`
|
|
60
|
+
- `allocate(ratios)` (largest remainder, ties to the earliest, the parts always sum to the whole),
|
|
61
|
+
`split(n)`
|
|
62
|
+
- `sumByCurrency(list)`: one sum per currency, sorted by code
|
|
63
|
+
- `Rate.percent`, `Rate.factor`, `Rate.ratio(a, b)`, `multiply`, `divide`, `add`, `subtract`,
|
|
64
|
+
`compare`, `toFixed(decimals, mode)`, `toFactor()`, `toPercent()`
|
|
65
|
+
- `Price.parse("NOK 0.0035")`, `Price.of`, `Price.fromMoney`, `Price.per(total, units)`, `add`,
|
|
66
|
+
`subtract`, `scale(rate)`, `times(quantity, mode)`
|
|
67
|
+
- `FxRate.parse("EUR/NOK 11.7352")`, `FxRate.of`, `FxRate.cross(a, b)`, `invert()`;
|
|
68
|
+
`convert(money, fxRate, mode)`
|
|
69
|
+
- `taxOf(net, rate, mode)` per line; `taxByRate(lines, mode)` per document: the taxable amount
|
|
70
|
+
summed per rate, the tax rounded once per rate (EN 16931 style)
|
|
71
|
+
- `currencyExponent(code)`, `isCurrency(code)`, `CURRENCIES`, `CURRENCY_EXPONENTS`,
|
|
72
|
+
`ISO_4217_VERSION`, `MONEY_PATTERN` (for JSON Schema)
|
|
73
|
+
- Rounding modes: `half-up` (`DEFAULT_ROUNDING`), `half-even`, `down`, `up`. Errors are
|
|
74
|
+
`MoneyError` with a `code`: `invalid_money`, `unknown_currency`, `too_many_decimals`,
|
|
75
|
+
`currency_mismatch`, `amount_too_large`, `invalid_rate`, `invalid_rounding`, `division_by_zero`,
|
|
76
|
+
`invalid_ratios`, `invalid_decimal`.
|
|
77
|
+
|
|
78
|
+
## Develop
|
|
79
|
+
|
|
80
|
+
`bun run check` (Biome and `tsc`), `bun run test`, `bun run build` (ESM and `.d.ts` in `dist/`).
|
|
81
|
+
The package has no dependencies and imports nothing outside `src/`. Its `biome.json` says
|
|
82
|
+
`"root": false` while it lives in the Kennra monorepo; set it to `true` in a repository of its own.
|
|
83
|
+
|
|
84
|
+
The exponent table is generated from SIX's `list-one.xml`: update `src/currencies.ts` and
|
|
85
|
+
`ISO_4217_VERSION` together when a new list is published.
|
|
86
|
+
|
|
87
|
+
MIT licensed.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ISO 4217 exponent table: how many decimals each active currency has (minor units per major
|
|
3
|
+
* unit is 10^exponent). Versioned: regenerate it from the source when SIX publishes a new list,
|
|
4
|
+
* and change `ISO_4217_VERSION` with it.
|
|
5
|
+
*
|
|
6
|
+
* Source: ISO 4217 List One (current currency and funds codes), as published by SIX Financial
|
|
7
|
+
* Information on 2026-09-17 (`list-one.xml`, attribute `Pblshd`). Codes without minor units
|
|
8
|
+
* (`N.A.`: precious metals, SDR, testing codes and XXX) are left out, so they are not money here.
|
|
9
|
+
*/
|
|
10
|
+
export declare const ISO_4217_VERSION = "2026-09-17";
|
|
11
|
+
export type CurrencyExponent = 0 | 2 | 3 | 4;
|
|
12
|
+
export declare const CURRENCY_EXPONENTS: Readonly<Record<string, CurrencyExponent>>;
|
|
13
|
+
/** Every active ISO 4217 code with minor units, sorted. */
|
|
14
|
+
export declare const CURRENCIES: readonly string[];
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ISO 4217 exponent table: how many decimals each active currency has (minor units per major
|
|
3
|
+
* unit is 10^exponent). Versioned: regenerate it from the source when SIX publishes a new list,
|
|
4
|
+
* and change `ISO_4217_VERSION` with it.
|
|
5
|
+
*
|
|
6
|
+
* Source: ISO 4217 List One (current currency and funds codes), as published by SIX Financial
|
|
7
|
+
* Information on 2026-09-17 (`list-one.xml`, attribute `Pblshd`). Codes without minor units
|
|
8
|
+
* (`N.A.`: precious metals, SDR, testing codes and XXX) are left out, so they are not money here.
|
|
9
|
+
*/
|
|
10
|
+
export const ISO_4217_VERSION = '2026-09-17';
|
|
11
|
+
// biome-ignore format: one table, a dozen codes a line
|
|
12
|
+
export const CURRENCY_EXPONENTS = Object.freeze({
|
|
13
|
+
AED: 2, AFN: 2, ALL: 2, AMD: 2, AOA: 2, ARS: 2, AUD: 2, AWG: 2, AZN: 2, BAM: 2, BBD: 2, BDT: 2,
|
|
14
|
+
BHD: 3, BIF: 0, BMD: 2, BND: 2, BOB: 2, BOV: 2, BRL: 2, BSD: 2, BTN: 2, BWP: 2, BYN: 2, BZD: 2,
|
|
15
|
+
CAD: 2, CDF: 2, CHE: 2, CHF: 2, CHW: 2, CLF: 4, CLP: 0, CNY: 2, COP: 2, COU: 2, CRC: 2, CUP: 2,
|
|
16
|
+
CVE: 2, CZK: 2, DJF: 0, DKK: 2, DOP: 2, DZD: 2, EGP: 2, ERN: 2, ETB: 2, EUR: 2, FJD: 2, FKP: 2,
|
|
17
|
+
GBP: 2, GEL: 2, GHS: 2, GIP: 2, GMD: 2, GNF: 0, GTQ: 2, GYD: 2, HKD: 2, HNL: 2, HTG: 2, HUF: 2,
|
|
18
|
+
IDR: 2, ILS: 2, INR: 2, IQD: 3, IRR: 2, ISK: 0, JMD: 2, JOD: 3, JPY: 0, KES: 2, KGS: 2, KHR: 2,
|
|
19
|
+
KMF: 0, KPW: 2, KRW: 0, KWD: 3, KYD: 2, KZT: 2, LAK: 2, LBP: 2, LKR: 2, LRD: 2, LSL: 2, LYD: 3,
|
|
20
|
+
MAD: 2, MDL: 2, MGA: 2, MKD: 2, MMK: 2, MNT: 2, MOP: 2, MRU: 2, MUR: 2, MVR: 2, MWK: 2, MXN: 2,
|
|
21
|
+
MXV: 2, MYR: 2, MZN: 2, NAD: 2, NGN: 2, NIO: 2, NOK: 2, NPR: 2, NZD: 2, OMR: 3, PAB: 2, PEN: 2,
|
|
22
|
+
PGK: 2, PHP: 2, PKR: 2, PLN: 2, PYG: 0, QAR: 2, RON: 2, RSD: 2, RUB: 2, RWF: 0, SAR: 2, SBD: 2,
|
|
23
|
+
SCR: 2, SDG: 2, SEK: 2, SGD: 2, SHP: 2, SLE: 2, SOS: 2, SRD: 2, SSP: 2, STN: 2, SVC: 2, SYP: 2,
|
|
24
|
+
SZL: 2, THB: 2, TJS: 2, TMT: 2, TND: 3, TOP: 2, TRY: 2, TTD: 2, TWD: 2, TZS: 2, UAH: 2, UGX: 0,
|
|
25
|
+
USD: 2, USN: 2, UYI: 0, UYU: 2, UYW: 4, UZS: 2, VED: 2, VES: 2, VND: 0, VUV: 0, WST: 2, XAD: 2,
|
|
26
|
+
XAF: 0, XCD: 2, XCG: 2, XOF: 0, XPF: 0, YER: 2, ZAR: 2, ZMW: 2, ZWG: 2,
|
|
27
|
+
});
|
|
28
|
+
/** Every active ISO 4217 code with minor units, sorted. */
|
|
29
|
+
export const CURRENCIES = Object.freeze(Object.keys(CURRENCY_EXPONENTS).sort());
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exact decimal arithmetic on bigint: a value is a numerator over a positive denominator (a
|
|
3
|
+
* rational), and rounding happens once, where a result becomes Money. No floats anywhere.
|
|
4
|
+
*/
|
|
5
|
+
/** How a value is rounded where it becomes Money (or a fixed number of decimals). */
|
|
6
|
+
export type RoundingMode = 'half-up' | 'half-even' | 'down' | 'up';
|
|
7
|
+
/**
|
|
8
|
+
* `half-up`: half away from zero, the commercial rounding customers expect on invoices and quotes.
|
|
9
|
+
* `half-even` (banker's rounding) is there for ledgers that ask for it; `down` is toward zero and
|
|
10
|
+
* `up` away from zero.
|
|
11
|
+
*/
|
|
12
|
+
export declare const ROUNDING_MODES: readonly RoundingMode[];
|
|
13
|
+
/** The rounding for customer-facing amounts: half away from zero. */
|
|
14
|
+
export declare const DEFAULT_ROUNDING: RoundingMode;
|
|
15
|
+
/** Machine-readable error codes, the same as the group's payment service returns. */
|
|
16
|
+
export type MoneyErrorCode = 'invalid_money' | 'invalid_decimal' | 'unknown_currency' | 'too_many_decimals' | 'currency_mismatch' | 'amount_too_large' | 'invalid_rounding' | 'division_by_zero' | 'invalid_ratios' | 'invalid_rate';
|
|
17
|
+
export declare class MoneyError extends Error {
|
|
18
|
+
readonly code: MoneyErrorCode;
|
|
19
|
+
constructor(code: MoneyErrorCode, message: string);
|
|
20
|
+
}
|
|
21
|
+
export declare const pow10: (n: number) => bigint;
|
|
22
|
+
export declare function assertRounding(mode: unknown): asserts mode is RoundingMode;
|
|
23
|
+
/** num / den rounded to an integer with `mode`. `den` may be negative; it must not be zero. */
|
|
24
|
+
export declare function divRound(num: bigint, den: bigint, mode: RoundingMode): bigint;
|
|
25
|
+
/** A plain decimal string: digits, optional `-`, optional `.` and decimals. */
|
|
26
|
+
export interface ParsedDecimal {
|
|
27
|
+
/** The value times 10^scale. */
|
|
28
|
+
units: bigint;
|
|
29
|
+
/** How many decimals the string had. */
|
|
30
|
+
scale: number;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Parses `-12.345` exactly. No thousands separators, no exponent, no `+`, no leading zeros, `.`
|
|
34
|
+
* as the decimal mark, at least one digit before it.
|
|
35
|
+
*/
|
|
36
|
+
export declare function parseDecimal(s: string, what?: string): ParsedDecimal;
|
|
37
|
+
/** `units / 10^scale` as a decimal string with exactly `scale` decimals. */
|
|
38
|
+
export declare function formatUnits(units: bigint, scale: number): string;
|
|
39
|
+
/**
|
|
40
|
+
* `units / 10^scale` as units of `10^-decimals`, when that is exact: extra decimals are accepted
|
|
41
|
+
* only when they are all zero (`"4.990"` as 2 decimals is 499). Null when a non-zero digit would be
|
|
42
|
+
* lost.
|
|
43
|
+
*/
|
|
44
|
+
export declare function rescale(units: bigint, scale: number, decimals: number): bigint | null;
|
|
45
|
+
/** Drops trailing zero decimals: `1.2500` → `1.25`, `3.000` → `3`. */
|
|
46
|
+
export declare function trimZeros(s: string): string;
|
package/dist/decimal.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exact decimal arithmetic on bigint: a value is a numerator over a positive denominator (a
|
|
3
|
+
* rational), and rounding happens once, where a result becomes Money. No floats anywhere.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* `half-up`: half away from zero, the commercial rounding customers expect on invoices and quotes.
|
|
7
|
+
* `half-even` (banker's rounding) is there for ledgers that ask for it; `down` is toward zero and
|
|
8
|
+
* `up` away from zero.
|
|
9
|
+
*/
|
|
10
|
+
export const ROUNDING_MODES = ['half-up', 'half-even', 'down', 'up'];
|
|
11
|
+
/** The rounding for customer-facing amounts: half away from zero. */
|
|
12
|
+
export const DEFAULT_ROUNDING = 'half-up';
|
|
13
|
+
export class MoneyError extends Error {
|
|
14
|
+
code;
|
|
15
|
+
constructor(code, message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.name = 'MoneyError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export const pow10 = (n) => 10n ** BigInt(n);
|
|
22
|
+
const abs = (n) => (n < 0n ? -n : n);
|
|
23
|
+
export function assertRounding(mode) {
|
|
24
|
+
if (!ROUNDING_MODES.includes(mode))
|
|
25
|
+
throw new MoneyError('invalid_rounding', `Rounding mode must be one of ${ROUNDING_MODES.join(', ')}, got ${String(mode)}`);
|
|
26
|
+
}
|
|
27
|
+
/** num / den rounded to an integer with `mode`. `den` may be negative; it must not be zero. */
|
|
28
|
+
export function divRound(num, den, mode) {
|
|
29
|
+
assertRounding(mode);
|
|
30
|
+
if (den === 0n)
|
|
31
|
+
throw new MoneyError('division_by_zero', 'Division by zero');
|
|
32
|
+
if (den < 0n) {
|
|
33
|
+
num = -num;
|
|
34
|
+
den = -den;
|
|
35
|
+
}
|
|
36
|
+
const negative = num < 0n;
|
|
37
|
+
const n = abs(num);
|
|
38
|
+
let q = n / den;
|
|
39
|
+
const r = n % den;
|
|
40
|
+
if (r !== 0n) {
|
|
41
|
+
const twice = 2n * r;
|
|
42
|
+
const away = mode === 'up' ||
|
|
43
|
+
(mode === 'half-up' && twice >= den) ||
|
|
44
|
+
(mode === 'half-even' && (twice > den || (twice === den && q % 2n === 1n)));
|
|
45
|
+
if (away)
|
|
46
|
+
q += 1n;
|
|
47
|
+
}
|
|
48
|
+
return negative ? -q : q;
|
|
49
|
+
}
|
|
50
|
+
const DECIMAL_RE = /^(-?)(0|[1-9]\d*)(?:\.(\d+))?$/;
|
|
51
|
+
/**
|
|
52
|
+
* Parses `-12.345` exactly. No thousands separators, no exponent, no `+`, no leading zeros, `.`
|
|
53
|
+
* as the decimal mark, at least one digit before it.
|
|
54
|
+
*/
|
|
55
|
+
export function parseDecimal(s, what = 'decimal') {
|
|
56
|
+
const m = typeof s === 'string' ? DECIMAL_RE.exec(s) : null;
|
|
57
|
+
if (!m)
|
|
58
|
+
throw new MoneyError('invalid_decimal', `Not a ${what}: ${JSON.stringify(s)} (digits with "." as the decimal mark, no separators)`);
|
|
59
|
+
const frac = m[3] ?? '';
|
|
60
|
+
const units = BigInt(`${m[2]}${frac}`);
|
|
61
|
+
return { units: m[1] ? -units : units, scale: frac.length };
|
|
62
|
+
}
|
|
63
|
+
/** `units / 10^scale` as a decimal string with exactly `scale` decimals. */
|
|
64
|
+
export function formatUnits(units, scale) {
|
|
65
|
+
const negative = units < 0n;
|
|
66
|
+
const digits = abs(units)
|
|
67
|
+
.toString()
|
|
68
|
+
.padStart(scale + 1, '0');
|
|
69
|
+
const int = digits.slice(0, digits.length - scale);
|
|
70
|
+
const frac = scale ? `.${digits.slice(digits.length - scale)}` : '';
|
|
71
|
+
return `${negative ? '-' : ''}${int}${frac}`;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* `units / 10^scale` as units of `10^-decimals`, when that is exact: extra decimals are accepted
|
|
75
|
+
* only when they are all zero (`"4.990"` as 2 decimals is 499). Null when a non-zero digit would be
|
|
76
|
+
* lost.
|
|
77
|
+
*/
|
|
78
|
+
export function rescale(units, scale, decimals) {
|
|
79
|
+
if (scale <= decimals)
|
|
80
|
+
return units * pow10(decimals - scale);
|
|
81
|
+
const f = pow10(scale - decimals);
|
|
82
|
+
return units % f === 0n ? units / f : null;
|
|
83
|
+
}
|
|
84
|
+
/** Drops trailing zero decimals: `1.2500` → `1.25`, `3.000` → `3`. */
|
|
85
|
+
export function trimZeros(s) {
|
|
86
|
+
return s.includes('.') ? s.replace(/\.?0+$/, '') : s;
|
|
87
|
+
}
|
package/dist/fx.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type RoundingMode } from './decimal.ts';
|
|
2
|
+
import { Money } from './money.ts';
|
|
3
|
+
import { Rate } from './rate.ts';
|
|
4
|
+
/**
|
|
5
|
+
* An exchange rate for a currency pair: `"EUR/NOK 11.7352"` is 11.7352 NOK for one EUR. Up to 10
|
|
6
|
+
* decimals, positive. Dates belong to the caller: a rate is always picked for a day.
|
|
7
|
+
*/
|
|
8
|
+
export declare class FxRate {
|
|
9
|
+
/** The currency one unit of which the rate prices (EUR in EUR/NOK). */
|
|
10
|
+
readonly base: string;
|
|
11
|
+
/** The currency the rate is quoted in (NOK in EUR/NOK). */
|
|
12
|
+
readonly quote: string;
|
|
13
|
+
/** Units of `quote` per one unit of `base`, exact. */
|
|
14
|
+
readonly rate: Rate;
|
|
15
|
+
private constructor();
|
|
16
|
+
/** `"EUR/NOK 11.7352"`. */
|
|
17
|
+
static parse(s: string): FxRate;
|
|
18
|
+
/** `FxRate.of("EUR", "NOK", "11.7352")`, or an exact Rate. */
|
|
19
|
+
static of(base: string, quote: string, rate: string | Rate): FxRate;
|
|
20
|
+
/** The other way round: EUR/NOK 11.7352 → NOK/EUR 1/11.7352 (exact). */
|
|
21
|
+
invert(): FxRate;
|
|
22
|
+
/**
|
|
23
|
+
* A cross rate through a common base: `EUR/NOK` and `EUR/SEK` give `NOK/SEK`, exactly. The bases
|
|
24
|
+
* must match.
|
|
25
|
+
*/
|
|
26
|
+
static cross(from: FxRate, to: FxRate): FxRate;
|
|
27
|
+
/** `"EUR/NOK 11.7352"` (a quotient with no exact form is shown rounded to 10 decimals). */
|
|
28
|
+
toString(): string;
|
|
29
|
+
toJSON(): string;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Converts money at an explicit exchange rate, rounded once to the target currency's decimals.
|
|
33
|
+
* The pair must fit the money: NOK at EUR/NOK goes to EUR (divides), EUR at EUR/NOK to NOK
|
|
34
|
+
* (multiplies); any other currency is an error.
|
|
35
|
+
*/
|
|
36
|
+
export declare function convert(money: Money, fx: FxRate, mode: RoundingMode): Money;
|
package/dist/fx.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { divRound, MoneyError, pow10 } from "./decimal.js";
|
|
2
|
+
import { currencyExponent, Money } from "./money.js";
|
|
3
|
+
import { parseExact, Rate } from "./rate.js";
|
|
4
|
+
const FX_RE = /^([A-Z]{3})\/([A-Z]{3}) (\S+)$/;
|
|
5
|
+
/**
|
|
6
|
+
* An exchange rate for a currency pair: `"EUR/NOK 11.7352"` is 11.7352 NOK for one EUR. Up to 10
|
|
7
|
+
* decimals, positive. Dates belong to the caller: a rate is always picked for a day.
|
|
8
|
+
*/
|
|
9
|
+
export class FxRate {
|
|
10
|
+
base;
|
|
11
|
+
quote;
|
|
12
|
+
rate;
|
|
13
|
+
constructor(
|
|
14
|
+
/** The currency one unit of which the rate prices (EUR in EUR/NOK). */
|
|
15
|
+
base,
|
|
16
|
+
/** The currency the rate is quoted in (NOK in EUR/NOK). */
|
|
17
|
+
quote,
|
|
18
|
+
/** Units of `quote` per one unit of `base`, exact. */
|
|
19
|
+
rate) {
|
|
20
|
+
this.base = base;
|
|
21
|
+
this.quote = quote;
|
|
22
|
+
this.rate = rate;
|
|
23
|
+
}
|
|
24
|
+
/** `"EUR/NOK 11.7352"`. */
|
|
25
|
+
static parse(s) {
|
|
26
|
+
const m = typeof s === 'string' ? FX_RE.exec(s) : null;
|
|
27
|
+
if (!m)
|
|
28
|
+
throw new MoneyError('invalid_rate', `Not an exchange rate: ${JSON.stringify(s)} (write it as "EUR/NOK 11.7352")`);
|
|
29
|
+
return FxRate.of(m[1], m[2], m[3]);
|
|
30
|
+
}
|
|
31
|
+
/** `FxRate.of("EUR", "NOK", "11.7352")`, or an exact Rate. */
|
|
32
|
+
static of(base, quote, rate) {
|
|
33
|
+
currencyExponent(base);
|
|
34
|
+
currencyExponent(quote);
|
|
35
|
+
let r = rate;
|
|
36
|
+
if (typeof r === 'string') {
|
|
37
|
+
const { num, den } = parseExact(r, 'exchange rate');
|
|
38
|
+
r = Rate.fraction(num, den);
|
|
39
|
+
}
|
|
40
|
+
if (r.isZero() || r.isNegative())
|
|
41
|
+
throw new MoneyError('invalid_rate', `An exchange rate is positive: ${base}/${quote} ${r}`);
|
|
42
|
+
return new FxRate(base, quote, r);
|
|
43
|
+
}
|
|
44
|
+
/** The other way round: EUR/NOK 11.7352 → NOK/EUR 1/11.7352 (exact). */
|
|
45
|
+
invert() {
|
|
46
|
+
return new FxRate(this.quote, this.base, Rate.fraction(1n, 1n).divide(this.rate));
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* A cross rate through a common base: `EUR/NOK` and `EUR/SEK` give `NOK/SEK`, exactly. The bases
|
|
50
|
+
* must match.
|
|
51
|
+
*/
|
|
52
|
+
static cross(from, to) {
|
|
53
|
+
if (from.base !== to.base)
|
|
54
|
+
throw new MoneyError('currency_mismatch', `A cross rate needs one base: ${from.base}/${from.quote} and ${to.base}/${to.quote}`);
|
|
55
|
+
return new FxRate(from.quote, to.quote, to.rate.divide(from.rate));
|
|
56
|
+
}
|
|
57
|
+
/** `"EUR/NOK 11.7352"` (a quotient with no exact form is shown rounded to 10 decimals). */
|
|
58
|
+
toString() {
|
|
59
|
+
return `${this.base}/${this.quote} ${this.rate.toFactor()}`;
|
|
60
|
+
}
|
|
61
|
+
toJSON() {
|
|
62
|
+
return this.toString();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Converts money at an explicit exchange rate, rounded once to the target currency's decimals.
|
|
67
|
+
* The pair must fit the money: NOK at EUR/NOK goes to EUR (divides), EUR at EUR/NOK to NOK
|
|
68
|
+
* (multiplies); any other currency is an error.
|
|
69
|
+
*/
|
|
70
|
+
export function convert(money, fx, mode) {
|
|
71
|
+
let to;
|
|
72
|
+
let factor;
|
|
73
|
+
if (money.currency === fx.base) {
|
|
74
|
+
to = fx.quote;
|
|
75
|
+
factor = fx.rate;
|
|
76
|
+
}
|
|
77
|
+
else if (money.currency === fx.quote) {
|
|
78
|
+
to = fx.base;
|
|
79
|
+
factor = Rate.fraction(1n, 1n).divide(fx.rate);
|
|
80
|
+
}
|
|
81
|
+
else
|
|
82
|
+
throw new MoneyError('currency_mismatch', `${money.currency} cannot be converted at ${fx.base}/${fx.quote}`);
|
|
83
|
+
const num = money.minor * factor.num * pow10(currencyExponent(to));
|
|
84
|
+
const den = factor.den * pow10(money.exponent);
|
|
85
|
+
return Money.of(to, divRound(num, den, mode));
|
|
86
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @newnormal/money: one money format, `"NOK 499.00"`, exact bigint maths, no floats.
|
|
3
|
+
* Zero dependencies; runs on Bun, Node, Deno and edge runtimes.
|
|
4
|
+
*/
|
|
5
|
+
export { CURRENCIES, CURRENCY_EXPONENTS, type CurrencyExponent, ISO_4217_VERSION } from './currencies.ts';
|
|
6
|
+
export { DEFAULT_ROUNDING, MoneyError, type MoneyErrorCode, ROUNDING_MODES, type RoundingMode, } from './decimal.ts';
|
|
7
|
+
export { convert, FxRate } from './fx.ts';
|
|
8
|
+
export { currencyExponent, isCurrency, MONEY_PATTERN, Money, type MoneyObject, sumByCurrency, } from './money.ts';
|
|
9
|
+
export { Price } from './price.ts';
|
|
10
|
+
export { MAX_RATE_DECIMALS, type Quantity, Rate } from './rate.ts';
|
|
11
|
+
export { type TaxBreakdown, type TaxBreakdownLine, taxByRate, taxOf } from './tax.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @newnormal/money: one money format, `"NOK 499.00"`, exact bigint maths, no floats.
|
|
3
|
+
* Zero dependencies; runs on Bun, Node, Deno and edge runtimes.
|
|
4
|
+
*/
|
|
5
|
+
export { CURRENCIES, CURRENCY_EXPONENTS, ISO_4217_VERSION } from "./currencies.js";
|
|
6
|
+
export { DEFAULT_ROUNDING, MoneyError, ROUNDING_MODES, } from "./decimal.js";
|
|
7
|
+
export { convert, FxRate } from "./fx.js";
|
|
8
|
+
export { currencyExponent, isCurrency, MONEY_PATTERN, Money, sumByCurrency, } from "./money.js";
|
|
9
|
+
export { Price } from "./price.js";
|
|
10
|
+
export { MAX_RATE_DECIMALS, Rate } from "./rate.js";
|
|
11
|
+
export { taxByRate, taxOf } from "./tax.js";
|
package/dist/money.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { type CurrencyExponent } from './currencies.ts';
|
|
2
|
+
import { type RoundingMode } from './decimal.ts';
|
|
3
|
+
import { type Quantity, type Rate } from './rate.ts';
|
|
4
|
+
/** Whether `code` is an active ISO 4217 currency with minor units (upper case, e.g. `NOK`). */
|
|
5
|
+
export declare function isCurrency(code: unknown): code is string;
|
|
6
|
+
/** The currency's ISO 4217 exponent: 0 (JPY), 2 (NOK), 3 (KWD) or 4 (CLF). Unknown codes throw. */
|
|
7
|
+
export declare function currencyExponent(code: string): CurrencyExponent;
|
|
8
|
+
/** The object form, the same as the group's payment service uses. */
|
|
9
|
+
export interface MoneyObject {
|
|
10
|
+
currency: string;
|
|
11
|
+
/** The decimal value with the currency's decimals, e.g. `"499.00"`. */
|
|
12
|
+
value: string;
|
|
13
|
+
/** Minor units as a safe integer, e.g. `49900`. */
|
|
14
|
+
minor: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A pattern a canonical-or-input Money string matches (`"NOK 499"`, `"NOK 499.00"`, `"JPY -1200"`),
|
|
18
|
+
* for JSON Schema and form validation. Whether the currency exists and the number of decimals
|
|
19
|
+
* fits it is checked by `Money.parse`.
|
|
20
|
+
*/
|
|
21
|
+
export declare const MONEY_PATTERN = "^[A-Z]{3} -?(0|[1-9][0-9]*)(\\.[0-9]+)?$";
|
|
22
|
+
/** A factor: a Rate, or a whole number (bigint or safe integer). Never a float or a bare string. */
|
|
23
|
+
type Factor = Rate | bigint | number;
|
|
24
|
+
/**
|
|
25
|
+
* An amount in one currency, exact. The canonical form is `"<ISO 4217 code> <decimal>"`:
|
|
26
|
+
* `"NOK 499.00"`, `"ISK 4990"`, `"JPY 1200"`, `"KWD 1.250"`, `"NOK -3.81"`. No thousands
|
|
27
|
+
* separators, `.` as the decimal mark, exactly the currency's decimals, the minus sign right
|
|
28
|
+
* before the digits. Kept as a bigint of minor units; never a float.
|
|
29
|
+
*/
|
|
30
|
+
export declare class Money {
|
|
31
|
+
readonly currency: string;
|
|
32
|
+
/** The amount in minor units (øre, cent; yen for JPY). */
|
|
33
|
+
readonly minor: bigint;
|
|
34
|
+
private constructor();
|
|
35
|
+
/**
|
|
36
|
+
* Parses `"NOK 499.00"`. Fewer decimals than the currency has are fine (`"NOK 499"` is
|
|
37
|
+
* `"NOK 499.00"`), and so are extra decimals that are all zero (`"ISK 4990.00"` is `"ISK 4990"`);
|
|
38
|
+
* a non-zero extra digit is an error, never rounded (`"NOK 4.999"`). An unknown currency is an
|
|
39
|
+
* error.
|
|
40
|
+
*/
|
|
41
|
+
static parse(s: string): Money;
|
|
42
|
+
/** Like `parse`, null instead of an error. */
|
|
43
|
+
static tryParse(s: unknown): Money | null;
|
|
44
|
+
/** Whether `s` is valid Money input (canonical, or with fewer decimals or extra zeros). */
|
|
45
|
+
static isMoney(s: unknown): s is string;
|
|
46
|
+
/**
|
|
47
|
+
* An amount from a currency and a decimal string (`Money.of("NOK", "499.5")`) or a bigint of
|
|
48
|
+
* minor units (`Money.of("NOK", 49950n)`).
|
|
49
|
+
*/
|
|
50
|
+
static of(currency: string, amount: string | bigint): Money;
|
|
51
|
+
/** An amount from minor units: a bigint, or a number that is a safe integer. */
|
|
52
|
+
static fromMinor(currency: string, minor: bigint | number): Money;
|
|
53
|
+
/** From the object form; `value` wins when both are given and they must agree. */
|
|
54
|
+
static fromObject(o: {
|
|
55
|
+
currency: string;
|
|
56
|
+
value?: string;
|
|
57
|
+
minor?: number | bigint | string;
|
|
58
|
+
}): Money;
|
|
59
|
+
static zero(currency: string): Money;
|
|
60
|
+
/** The sum of amounts in one currency. Empty needs `currency`; mixed currencies throw. */
|
|
61
|
+
static sum(items: Iterable<Money>, currency?: string): Money;
|
|
62
|
+
/** The currency's decimals. */
|
|
63
|
+
get exponent(): CurrencyExponent;
|
|
64
|
+
/** The decimal value with exactly the currency's decimals: `"499.00"`, `"1200"`, `"-3.81"`. */
|
|
65
|
+
get value(): string;
|
|
66
|
+
/** Minor units as a number; throws past 2^53 − 1, where a number stops being exact. */
|
|
67
|
+
get minorNumber(): number;
|
|
68
|
+
/** `"NOK 499.00"`. */
|
|
69
|
+
toString(): string;
|
|
70
|
+
/** The canonical string, so JSON carries `"NOK 499.00"`. */
|
|
71
|
+
toJSON(): string;
|
|
72
|
+
/** `{ currency: "NOK", value: "499.00", minor: 49900 }`. */
|
|
73
|
+
toObject(): MoneyObject;
|
|
74
|
+
/**
|
|
75
|
+
* For people: `Intl.NumberFormat` with the currency's decimals (`"kr 499,00"` in nb-NO,
|
|
76
|
+
* `"NOK 499.00"` in en-GB). Options are passed on; the fraction digits default to the currency's.
|
|
77
|
+
*/
|
|
78
|
+
format(locale?: string | string[], options?: Intl.NumberFormatOptions): string;
|
|
79
|
+
private same;
|
|
80
|
+
/** Whether both are in the same currency (never throws). */
|
|
81
|
+
sameCurrency(other: Money): boolean;
|
|
82
|
+
add(other: Money): Money;
|
|
83
|
+
subtract(other: Money): Money;
|
|
84
|
+
negate(): Money;
|
|
85
|
+
abs(): Money;
|
|
86
|
+
isZero(): boolean;
|
|
87
|
+
isNegative(): boolean;
|
|
88
|
+
isPositive(): boolean;
|
|
89
|
+
/** −1, 0 or 1. Throws across currencies. */
|
|
90
|
+
compare(other: Money): -1 | 0 | 1;
|
|
91
|
+
/** Same currency and amount. Across currencies it is false (EUR 1 is not NOK 1); never throws. */
|
|
92
|
+
equals(other: Money): boolean;
|
|
93
|
+
greaterThan(other: Money): boolean;
|
|
94
|
+
lessThan(other: Money): boolean;
|
|
95
|
+
/** The amount times a factor (a Rate or a whole number), rounded once. */
|
|
96
|
+
multiply(factor: Factor, mode: RoundingMode): Money;
|
|
97
|
+
/** The amount divided by a divisor, rounded once. To split without losing øre, use `allocate`. */
|
|
98
|
+
divide(divisor: Factor, mode: RoundingMode): Money;
|
|
99
|
+
/**
|
|
100
|
+
* Splits the amount by `ratios` without losing or inventing a minor unit: the parts always sum to
|
|
101
|
+
* the amount. Largest remainder: every part gets its share rounded toward zero, then the minor
|
|
102
|
+
* units left go one each to the parts with the largest remainders, ties to the earliest.
|
|
103
|
+
* `NOK 100.00` by `[1, 1, 1]` is 33.34, 33.33, 33.33.
|
|
104
|
+
*/
|
|
105
|
+
allocate(ratios: readonly (Rate | Quantity)[]): Money[];
|
|
106
|
+
/** `allocate` into `n` equal parts. */
|
|
107
|
+
split(n: number): Money[];
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Sums per currency, never across. Sorted by currency code, so the order is stable and says
|
|
111
|
+
* nothing about size.
|
|
112
|
+
*/
|
|
113
|
+
export declare function sumByCurrency(items: Iterable<Money | null | undefined>): Money[];
|
|
114
|
+
export {};
|
package/dist/money.js
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { CURRENCY_EXPONENTS } from "./currencies.js";
|
|
2
|
+
import { divRound, formatUnits, MoneyError, parseDecimal, rescale } from "./decimal.js";
|
|
3
|
+
import { gcd, parseQuantity } from "./rate.js";
|
|
4
|
+
/** Whether `code` is an active ISO 4217 currency with minor units (upper case, e.g. `NOK`). */
|
|
5
|
+
export function isCurrency(code) {
|
|
6
|
+
return typeof code === 'string' && Object.hasOwn(CURRENCY_EXPONENTS, code);
|
|
7
|
+
}
|
|
8
|
+
/** The currency's ISO 4217 exponent: 0 (JPY), 2 (NOK), 3 (KWD) or 4 (CLF). Unknown codes throw. */
|
|
9
|
+
export function currencyExponent(code) {
|
|
10
|
+
if (!isCurrency(code))
|
|
11
|
+
throw new MoneyError('unknown_currency', `Unknown currency ${JSON.stringify(code)} (ISO 4217, upper case)`);
|
|
12
|
+
return CURRENCY_EXPONENTS[code];
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A pattern a canonical-or-input Money string matches (`"NOK 499"`, `"NOK 499.00"`, `"JPY -1200"`),
|
|
16
|
+
* for JSON Schema and form validation. Whether the currency exists and the number of decimals
|
|
17
|
+
* fits it is checked by `Money.parse`.
|
|
18
|
+
*/
|
|
19
|
+
export const MONEY_PATTERN = '^[A-Z]{3} -?(0|[1-9][0-9]*)(\\.[0-9]+)?$';
|
|
20
|
+
const MONEY_RE = /^([A-Z]{3}) (-?(?:0|[1-9]\d*)(?:\.\d+)?)$/;
|
|
21
|
+
const factorOf = (f) => {
|
|
22
|
+
if (typeof f === 'string')
|
|
23
|
+
throw new MoneyError('invalid_rate', `Say the unit: Rate.factor(${JSON.stringify(f)}) or Rate.percent(${JSON.stringify(f)})`);
|
|
24
|
+
return parseQuantity(f);
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* An amount in one currency, exact. The canonical form is `"<ISO 4217 code> <decimal>"`:
|
|
28
|
+
* `"NOK 499.00"`, `"ISK 4990"`, `"JPY 1200"`, `"KWD 1.250"`, `"NOK -3.81"`. No thousands
|
|
29
|
+
* separators, `.` as the decimal mark, exactly the currency's decimals, the minus sign right
|
|
30
|
+
* before the digits. Kept as a bigint of minor units; never a float.
|
|
31
|
+
*/
|
|
32
|
+
export class Money {
|
|
33
|
+
currency;
|
|
34
|
+
/** The amount in minor units (øre, cent; yen for JPY). */
|
|
35
|
+
minor;
|
|
36
|
+
constructor(currency, minor) {
|
|
37
|
+
this.currency = currency;
|
|
38
|
+
this.minor = minor === 0n ? 0n : minor; // no negative zero
|
|
39
|
+
}
|
|
40
|
+
// -------------------------------------------------------------------------
|
|
41
|
+
// Making money
|
|
42
|
+
/**
|
|
43
|
+
* Parses `"NOK 499.00"`. Fewer decimals than the currency has are fine (`"NOK 499"` is
|
|
44
|
+
* `"NOK 499.00"`), and so are extra decimals that are all zero (`"ISK 4990.00"` is `"ISK 4990"`);
|
|
45
|
+
* a non-zero extra digit is an error, never rounded (`"NOK 4.999"`). An unknown currency is an
|
|
46
|
+
* error.
|
|
47
|
+
*/
|
|
48
|
+
static parse(s) {
|
|
49
|
+
const m = typeof s === 'string' ? MONEY_RE.exec(s) : null;
|
|
50
|
+
if (!m)
|
|
51
|
+
throw new MoneyError('invalid_money', `Not money: ${JSON.stringify(s)} (write it as "NOK 499.00": an ISO 4217 code, one space, digits with "." as the decimal mark)`);
|
|
52
|
+
return Money.of(m[1], m[2]);
|
|
53
|
+
}
|
|
54
|
+
/** Like `parse`, null instead of an error. */
|
|
55
|
+
static tryParse(s) {
|
|
56
|
+
if (typeof s !== 'string')
|
|
57
|
+
return null;
|
|
58
|
+
try {
|
|
59
|
+
return Money.parse(s);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** Whether `s` is valid Money input (canonical, or with fewer decimals or extra zeros). */
|
|
66
|
+
static isMoney(s) {
|
|
67
|
+
return Money.tryParse(s) !== null;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* An amount from a currency and a decimal string (`Money.of("NOK", "499.5")`) or a bigint of
|
|
71
|
+
* minor units (`Money.of("NOK", 49950n)`).
|
|
72
|
+
*/
|
|
73
|
+
static of(currency, amount) {
|
|
74
|
+
const exp = currencyExponent(currency);
|
|
75
|
+
if (typeof amount === 'bigint')
|
|
76
|
+
return new Money(currency, amount);
|
|
77
|
+
const { units, scale } = parseDecimal(amount, 'decimal amount');
|
|
78
|
+
const minor = rescale(units, scale, exp);
|
|
79
|
+
if (minor === null)
|
|
80
|
+
throw new MoneyError('too_many_decimals', `${currency} has ${exp} decimals, got ${JSON.stringify(amount)} (money is never rounded on input)`);
|
|
81
|
+
return new Money(currency, minor);
|
|
82
|
+
}
|
|
83
|
+
/** An amount from minor units: a bigint, or a number that is a safe integer. */
|
|
84
|
+
static fromMinor(currency, minor) {
|
|
85
|
+
if (typeof minor === 'number' && !Number.isSafeInteger(minor))
|
|
86
|
+
throw new MoneyError('amount_too_large', `Minor units must be a safe integer, got ${minor}`);
|
|
87
|
+
return Money.of(currency, BigInt(minor));
|
|
88
|
+
}
|
|
89
|
+
/** From the object form; `value` wins when both are given and they must agree. */
|
|
90
|
+
static fromObject(o) {
|
|
91
|
+
const byValue = o.value !== undefined ? Money.of(o.currency, o.value) : null;
|
|
92
|
+
let byMinor = null;
|
|
93
|
+
if (typeof o.minor === 'string') {
|
|
94
|
+
if (!/^-?\d+$/.test(o.minor))
|
|
95
|
+
throw new MoneyError('invalid_money', `Minor units must be whole: ${o.minor}`);
|
|
96
|
+
byMinor = Money.of(o.currency, BigInt(o.minor));
|
|
97
|
+
}
|
|
98
|
+
else if (o.minor !== undefined)
|
|
99
|
+
byMinor = Money.fromMinor(o.currency, o.minor);
|
|
100
|
+
if (byValue && byMinor && byValue.minor !== byMinor.minor)
|
|
101
|
+
throw new MoneyError('invalid_money', `value ${o.value} and minor ${o.minor} disagree`);
|
|
102
|
+
const m = byValue ?? byMinor;
|
|
103
|
+
if (!m)
|
|
104
|
+
throw new MoneyError('invalid_money', 'Money needs a value or minor units');
|
|
105
|
+
return m;
|
|
106
|
+
}
|
|
107
|
+
static zero(currency) {
|
|
108
|
+
return Money.of(currency, 0n);
|
|
109
|
+
}
|
|
110
|
+
/** The sum of amounts in one currency. Empty needs `currency`; mixed currencies throw. */
|
|
111
|
+
static sum(items, currency) {
|
|
112
|
+
let total = currency ? Money.zero(currency) : null;
|
|
113
|
+
for (const m of items)
|
|
114
|
+
total = total ? total.add(m) : m;
|
|
115
|
+
if (!total)
|
|
116
|
+
throw new MoneyError('invalid_money', 'The sum of nothing needs a currency');
|
|
117
|
+
return total;
|
|
118
|
+
}
|
|
119
|
+
// -------------------------------------------------------------------------
|
|
120
|
+
// Reading it
|
|
121
|
+
/** The currency's decimals. */
|
|
122
|
+
get exponent() {
|
|
123
|
+
return currencyExponent(this.currency);
|
|
124
|
+
}
|
|
125
|
+
/** The decimal value with exactly the currency's decimals: `"499.00"`, `"1200"`, `"-3.81"`. */
|
|
126
|
+
get value() {
|
|
127
|
+
return formatUnits(this.minor, this.exponent);
|
|
128
|
+
}
|
|
129
|
+
/** Minor units as a number; throws past 2^53 − 1, where a number stops being exact. */
|
|
130
|
+
get minorNumber() {
|
|
131
|
+
if (this.minor > BigInt(Number.MAX_SAFE_INTEGER) || this.minor < BigInt(Number.MIN_SAFE_INTEGER))
|
|
132
|
+
throw new MoneyError('amount_too_large', `${this.toString()} has more minor units than a number holds exactly; use .minor (bigint)`);
|
|
133
|
+
return Number(this.minor);
|
|
134
|
+
}
|
|
135
|
+
/** `"NOK 499.00"`. */
|
|
136
|
+
toString() {
|
|
137
|
+
return `${this.currency} ${this.value}`;
|
|
138
|
+
}
|
|
139
|
+
/** The canonical string, so JSON carries `"NOK 499.00"`. */
|
|
140
|
+
toJSON() {
|
|
141
|
+
return this.toString();
|
|
142
|
+
}
|
|
143
|
+
/** `{ currency: "NOK", value: "499.00", minor: 49900 }`. */
|
|
144
|
+
toObject() {
|
|
145
|
+
return { currency: this.currency, value: this.value, minor: this.minorNumber };
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* For people: `Intl.NumberFormat` with the currency's decimals (`"kr 499,00"` in nb-NO,
|
|
149
|
+
* `"NOK 499.00"` in en-GB). Options are passed on; the fraction digits default to the currency's.
|
|
150
|
+
*/
|
|
151
|
+
format(locale, options) {
|
|
152
|
+
const exp = this.exponent;
|
|
153
|
+
const nf = new Intl.NumberFormat(locale, {
|
|
154
|
+
style: 'currency',
|
|
155
|
+
currency: this.currency,
|
|
156
|
+
minimumFractionDigits: exp,
|
|
157
|
+
maximumFractionDigits: exp,
|
|
158
|
+
...options,
|
|
159
|
+
});
|
|
160
|
+
// A decimal string keeps big amounts exact in engines with Intl.NumberFormat v3.
|
|
161
|
+
return nf.format(this.value);
|
|
162
|
+
}
|
|
163
|
+
// -------------------------------------------------------------------------
|
|
164
|
+
// Same-currency maths
|
|
165
|
+
same(other) {
|
|
166
|
+
if (!(other instanceof Money))
|
|
167
|
+
throw new MoneyError('invalid_money', 'Expected Money');
|
|
168
|
+
if (other.currency !== this.currency)
|
|
169
|
+
throw new MoneyError('currency_mismatch', `${this.currency} and ${other.currency} cannot be added or compared without an exchange rate`);
|
|
170
|
+
return other;
|
|
171
|
+
}
|
|
172
|
+
/** Whether both are in the same currency (never throws). */
|
|
173
|
+
sameCurrency(other) {
|
|
174
|
+
return other.currency === this.currency;
|
|
175
|
+
}
|
|
176
|
+
add(other) {
|
|
177
|
+
return new Money(this.currency, this.minor + this.same(other).minor);
|
|
178
|
+
}
|
|
179
|
+
subtract(other) {
|
|
180
|
+
return new Money(this.currency, this.minor - this.same(other).minor);
|
|
181
|
+
}
|
|
182
|
+
negate() {
|
|
183
|
+
return new Money(this.currency, -this.minor);
|
|
184
|
+
}
|
|
185
|
+
abs() {
|
|
186
|
+
return this.minor < 0n ? this.negate() : this;
|
|
187
|
+
}
|
|
188
|
+
isZero() {
|
|
189
|
+
return this.minor === 0n;
|
|
190
|
+
}
|
|
191
|
+
isNegative() {
|
|
192
|
+
return this.minor < 0n;
|
|
193
|
+
}
|
|
194
|
+
isPositive() {
|
|
195
|
+
return this.minor > 0n;
|
|
196
|
+
}
|
|
197
|
+
/** −1, 0 or 1. Throws across currencies. */
|
|
198
|
+
compare(other) {
|
|
199
|
+
const o = this.same(other).minor;
|
|
200
|
+
return this.minor < o ? -1 : this.minor > o ? 1 : 0;
|
|
201
|
+
}
|
|
202
|
+
/** Same currency and amount. Across currencies it is false (EUR 1 is not NOK 1); never throws. */
|
|
203
|
+
equals(other) {
|
|
204
|
+
return other instanceof Money && other.currency === this.currency && other.minor === this.minor;
|
|
205
|
+
}
|
|
206
|
+
greaterThan(other) {
|
|
207
|
+
return this.compare(other) > 0;
|
|
208
|
+
}
|
|
209
|
+
lessThan(other) {
|
|
210
|
+
return this.compare(other) < 0;
|
|
211
|
+
}
|
|
212
|
+
// -------------------------------------------------------------------------
|
|
213
|
+
// Where rounding happens: always with a named mode
|
|
214
|
+
/** The amount times a factor (a Rate or a whole number), rounded once. */
|
|
215
|
+
multiply(factor, mode) {
|
|
216
|
+
const r = factorOf(factor);
|
|
217
|
+
return new Money(this.currency, divRound(this.minor * r.num, r.den, mode));
|
|
218
|
+
}
|
|
219
|
+
/** The amount divided by a divisor, rounded once. To split without losing øre, use `allocate`. */
|
|
220
|
+
divide(divisor, mode) {
|
|
221
|
+
const r = factorOf(divisor);
|
|
222
|
+
if (r.num === 0n)
|
|
223
|
+
throw new MoneyError('division_by_zero', 'Division by zero');
|
|
224
|
+
return new Money(this.currency, divRound(this.minor * r.den, r.num, mode));
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Splits the amount by `ratios` without losing or inventing a minor unit: the parts always sum to
|
|
228
|
+
* the amount. Largest remainder: every part gets its share rounded toward zero, then the minor
|
|
229
|
+
* units left go one each to the parts with the largest remainders, ties to the earliest.
|
|
230
|
+
* `NOK 100.00` by `[1, 1, 1]` is 33.34, 33.33, 33.33.
|
|
231
|
+
*/
|
|
232
|
+
allocate(ratios) {
|
|
233
|
+
if (!ratios.length)
|
|
234
|
+
throw new MoneyError('invalid_ratios', 'allocate needs at least one ratio');
|
|
235
|
+
const rs = ratios.map((r) => parseQuantity(r));
|
|
236
|
+
if (rs.some((r) => r.num < 0n))
|
|
237
|
+
throw new MoneyError('invalid_ratios', 'Ratios cannot be negative');
|
|
238
|
+
// Common denominator: every ratio as a whole number over `den`.
|
|
239
|
+
let den = 1n;
|
|
240
|
+
for (const r of rs)
|
|
241
|
+
den = (den / gcd(den, r.den)) * r.den;
|
|
242
|
+
const weights = rs.map((r) => r.num * (den / r.den));
|
|
243
|
+
const total = weights.reduce((a, b) => a + b, 0n);
|
|
244
|
+
if (total === 0n)
|
|
245
|
+
throw new MoneyError('invalid_ratios', 'Ratios cannot all be zero');
|
|
246
|
+
const sign = this.minor < 0n ? -1n : 1n;
|
|
247
|
+
const amount = this.minor * sign;
|
|
248
|
+
const parts = weights.map((w) => (amount * w) / total);
|
|
249
|
+
const remainders = weights.map((w, i) => ({ i, r: (amount * w) % total }));
|
|
250
|
+
let left = amount - parts.reduce((a, b) => a + b, 0n);
|
|
251
|
+
remainders.sort((a, b) => (a.r === b.r ? a.i - b.i : a.r > b.r ? -1 : 1));
|
|
252
|
+
for (let k = 0; left > 0n; k++, left--)
|
|
253
|
+
parts[remainders[k % remainders.length].i] += 1n;
|
|
254
|
+
return parts.map((p) => new Money(this.currency, p * sign));
|
|
255
|
+
}
|
|
256
|
+
/** `allocate` into `n` equal parts. */
|
|
257
|
+
split(n) {
|
|
258
|
+
if (!Number.isSafeInteger(n) || n < 1)
|
|
259
|
+
throw new MoneyError('invalid_ratios', 'split needs a whole number ≥ 1');
|
|
260
|
+
return this.allocate(Array.from({ length: n }, () => 1n));
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Sums per currency, never across. Sorted by currency code, so the order is stable and says
|
|
265
|
+
* nothing about size.
|
|
266
|
+
*/
|
|
267
|
+
export function sumByCurrency(items) {
|
|
268
|
+
const m = new Map();
|
|
269
|
+
for (const i of items) {
|
|
270
|
+
if (!i)
|
|
271
|
+
continue;
|
|
272
|
+
const prev = m.get(i.currency);
|
|
273
|
+
m.set(i.currency, prev ? prev.add(i) : i);
|
|
274
|
+
}
|
|
275
|
+
return [...m.values()].sort((a, b) => (a.currency < b.currency ? -1 : a.currency > b.currency ? 1 : 0));
|
|
276
|
+
}
|
package/dist/price.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type RoundingMode } from './decimal.ts';
|
|
2
|
+
import { Money } from './money.ts';
|
|
3
|
+
import { type Quantity, Rate } from './rate.ts';
|
|
4
|
+
/**
|
|
5
|
+
* A unit price with a currency and more precision than money has (usage pricing: `"NOK 0.0035"`
|
|
6
|
+
* per API call; a daily rate for proration). Up to 10 decimals, sign allowed. Prices add up within
|
|
7
|
+
* one currency, but a Price is never added to Money: it becomes Money in one place,
|
|
8
|
+
* `times(quantity, mode)`, rounded once.
|
|
9
|
+
*/
|
|
10
|
+
export declare class Price {
|
|
11
|
+
readonly currency: string;
|
|
12
|
+
/** The amount per unit as an exact fraction of major units. */
|
|
13
|
+
readonly amount: Rate;
|
|
14
|
+
private constructor();
|
|
15
|
+
/** `"NOK 0.0035"`. */
|
|
16
|
+
static parse(s: string): Price;
|
|
17
|
+
/** A price from a currency and a decimal string with up to 10 decimals. */
|
|
18
|
+
static of(currency: string, amount: string): Price;
|
|
19
|
+
/** Money as a price per unit (`NOK 499.00` per unit). */
|
|
20
|
+
static fromMoney(m: Money): Price;
|
|
21
|
+
/** The exact price of one unit when `total` is spread over `units` (a monthly price per day). */
|
|
22
|
+
static per(total: Money, units: Quantity): Price;
|
|
23
|
+
private same;
|
|
24
|
+
add(other: Price): Price;
|
|
25
|
+
subtract(other: Price): Price;
|
|
26
|
+
/** The price times a dimensionless rate (a discount, a markup), still a Price. */
|
|
27
|
+
scale(rate: Rate): Price;
|
|
28
|
+
/** The price of `quantity` units (`"1.5"`, `3`, `3n`), rounded once to the currency's decimals. */
|
|
29
|
+
times(quantity: Quantity, mode: RoundingMode): Money;
|
|
30
|
+
/**
|
|
31
|
+
* `"NOK 0.0035"`: at least the currency's decimals, more only where the price has them (a
|
|
32
|
+
* quotient with no exact form within 10 decimals is shown rounded half-up to 10).
|
|
33
|
+
*/
|
|
34
|
+
toString(): string;
|
|
35
|
+
toJSON(): string;
|
|
36
|
+
}
|
package/dist/price.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { divRound, formatUnits, MoneyError, pow10 } from "./decimal.js";
|
|
2
|
+
import { currencyExponent, Money } from "./money.js";
|
|
3
|
+
import { MAX_RATE_DECIMALS, parseExact, parseQuantity, Rate } from "./rate.js";
|
|
4
|
+
const PRICE_RE = /^([A-Z]{3}) (\S+)$/;
|
|
5
|
+
/**
|
|
6
|
+
* A unit price with a currency and more precision than money has (usage pricing: `"NOK 0.0035"`
|
|
7
|
+
* per API call; a daily rate for proration). Up to 10 decimals, sign allowed. Prices add up within
|
|
8
|
+
* one currency, but a Price is never added to Money: it becomes Money in one place,
|
|
9
|
+
* `times(quantity, mode)`, rounded once.
|
|
10
|
+
*/
|
|
11
|
+
export class Price {
|
|
12
|
+
currency;
|
|
13
|
+
amount;
|
|
14
|
+
constructor(currency,
|
|
15
|
+
/** The amount per unit as an exact fraction of major units. */
|
|
16
|
+
amount) {
|
|
17
|
+
this.currency = currency;
|
|
18
|
+
this.amount = amount;
|
|
19
|
+
}
|
|
20
|
+
/** `"NOK 0.0035"`. */
|
|
21
|
+
static parse(s) {
|
|
22
|
+
const m = typeof s === 'string' ? PRICE_RE.exec(s) : null;
|
|
23
|
+
if (!m)
|
|
24
|
+
throw new MoneyError('invalid_money', `Not a price: ${JSON.stringify(s)} (write it as "NOK 0.0035")`);
|
|
25
|
+
return Price.of(m[1], m[2]);
|
|
26
|
+
}
|
|
27
|
+
/** A price from a currency and a decimal string with up to 10 decimals. */
|
|
28
|
+
static of(currency, amount) {
|
|
29
|
+
currencyExponent(currency);
|
|
30
|
+
const { num, den } = parseExact(amount, 'price');
|
|
31
|
+
return new Price(currency, Rate.fraction(num, den));
|
|
32
|
+
}
|
|
33
|
+
/** Money as a price per unit (`NOK 499.00` per unit). */
|
|
34
|
+
static fromMoney(m) {
|
|
35
|
+
return new Price(m.currency, Rate.fraction(m.minor, pow10(m.exponent)));
|
|
36
|
+
}
|
|
37
|
+
/** The exact price of one unit when `total` is spread over `units` (a monthly price per day). */
|
|
38
|
+
static per(total, units) {
|
|
39
|
+
const q = parseQuantity(units);
|
|
40
|
+
if (q.num === 0n)
|
|
41
|
+
throw new MoneyError('division_by_zero', 'A price per zero units');
|
|
42
|
+
return new Price(total.currency, Rate.fraction(total.minor * q.den, pow10(total.exponent) * q.num));
|
|
43
|
+
}
|
|
44
|
+
same(other) {
|
|
45
|
+
if (other.currency !== this.currency)
|
|
46
|
+
throw new MoneyError('currency_mismatch', `${this.currency} and ${other.currency} prices cannot be added`);
|
|
47
|
+
}
|
|
48
|
+
add(other) {
|
|
49
|
+
this.same(other);
|
|
50
|
+
return new Price(this.currency, this.amount.add(other.amount));
|
|
51
|
+
}
|
|
52
|
+
subtract(other) {
|
|
53
|
+
this.same(other);
|
|
54
|
+
return new Price(this.currency, this.amount.subtract(other.amount));
|
|
55
|
+
}
|
|
56
|
+
/** The price times a dimensionless rate (a discount, a markup), still a Price. */
|
|
57
|
+
scale(rate) {
|
|
58
|
+
return new Price(this.currency, this.amount.multiply(rate));
|
|
59
|
+
}
|
|
60
|
+
/** The price of `quantity` units (`"1.5"`, `3`, `3n`), rounded once to the currency's decimals. */
|
|
61
|
+
times(quantity, mode) {
|
|
62
|
+
const q = parseQuantity(quantity);
|
|
63
|
+
const exp = currencyExponent(this.currency);
|
|
64
|
+
const num = this.amount.num * q.num * pow10(exp);
|
|
65
|
+
return Money.of(this.currency, divRound(num, this.amount.den * q.den, mode));
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* `"NOK 0.0035"`: at least the currency's decimals, more only where the price has them (a
|
|
69
|
+
* quotient with no exact form within 10 decimals is shown rounded half-up to 10).
|
|
70
|
+
*/
|
|
71
|
+
toString() {
|
|
72
|
+
let decimals = currencyExponent(this.currency);
|
|
73
|
+
while (decimals < MAX_RATE_DECIMALS && !this.amount.isExact(decimals))
|
|
74
|
+
decimals++;
|
|
75
|
+
const units = divRound(this.amount.num * pow10(decimals), this.amount.den, 'half-up');
|
|
76
|
+
return `${this.currency} ${formatUnits(units, decimals)}`;
|
|
77
|
+
}
|
|
78
|
+
toJSON() {
|
|
79
|
+
return this.toString();
|
|
80
|
+
}
|
|
81
|
+
}
|
package/dist/rate.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { type RoundingMode } from './decimal.ts';
|
|
2
|
+
/** Most decimals a Rate, Price, FxRate or quantity may be written with. */
|
|
3
|
+
export declare const MAX_RATE_DECIMALS = 10;
|
|
4
|
+
export declare const gcd: (a: bigint, b: bigint) => bigint;
|
|
5
|
+
/** A decimal string with at most 10 decimals as an exact fraction. */
|
|
6
|
+
export declare function parseExact(s: string, what: string): {
|
|
7
|
+
num: bigint;
|
|
8
|
+
den: bigint;
|
|
9
|
+
};
|
|
10
|
+
/** A quantity or a whole number: an exact decimal string (`"1.5"`), a bigint or a safe integer. */
|
|
11
|
+
export type Quantity = string | bigint | number;
|
|
12
|
+
export declare function parseQuantity(q: Quantity | Rate): {
|
|
13
|
+
num: bigint;
|
|
14
|
+
den: bigint;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* A dimensionless rate, kept as an exact factor (a fraction of two bigints): a tax rate, a
|
|
18
|
+
* discount, a proration factor, a ratio. The constructor says the unit: `Rate.percent("25")` and
|
|
19
|
+
* `Rate.factor("0.25")` are the same rate. Up to 10 decimals, sign allowed. Products and quotients
|
|
20
|
+
* of rates lose nothing; a rate is rounded once, where it becomes Money.
|
|
21
|
+
*/
|
|
22
|
+
export declare class Rate {
|
|
23
|
+
/** Numerator of the factor. */
|
|
24
|
+
readonly num: bigint;
|
|
25
|
+
/** Denominator, always positive and in lowest terms with `num`. */
|
|
26
|
+
readonly den: bigint;
|
|
27
|
+
private constructor();
|
|
28
|
+
/** A factor: `Rate.factor("0.25")` is a quarter; `Rate.factor(2)` doubles. */
|
|
29
|
+
static factor(v: Quantity): Rate;
|
|
30
|
+
/** A percentage: `Rate.percent("25")` is the factor 0.25; `"12.5"` is 0.125. */
|
|
31
|
+
static percent(v: Quantity): Rate;
|
|
32
|
+
/** The exact quotient `a / b` of two whole numbers or factors (`Rate.ratio(10, 30)` is 1/3). */
|
|
33
|
+
static ratio(a: Quantity | Rate, b: Quantity | Rate): Rate;
|
|
34
|
+
/** @internal An exact fraction. */
|
|
35
|
+
static fraction(num: bigint, den: bigint): Rate;
|
|
36
|
+
multiply(other: Rate): Rate;
|
|
37
|
+
divide(other: Rate): Rate;
|
|
38
|
+
add(other: Rate): Rate;
|
|
39
|
+
subtract(other: Rate): Rate;
|
|
40
|
+
negate(): Rate;
|
|
41
|
+
isZero(): boolean;
|
|
42
|
+
isNegative(): boolean;
|
|
43
|
+
compare(other: Rate): -1 | 0 | 1;
|
|
44
|
+
equals(other: Rate): boolean;
|
|
45
|
+
/** Whether the factor has an exact decimal form with at most `decimals` decimals. */
|
|
46
|
+
isExact(decimals?: number): boolean;
|
|
47
|
+
/** The factor with exactly `decimals` decimals, rounded with `mode`. */
|
|
48
|
+
toFixed(decimals: number, mode: RoundingMode): string;
|
|
49
|
+
/**
|
|
50
|
+
* The factor as the shortest exact decimal (`"0.25"`). A factor with no exact form within 10
|
|
51
|
+
* decimals (1/3) is shown rounded half-up to 10 decimals; the maths keeps the exact fraction.
|
|
52
|
+
*/
|
|
53
|
+
toFactor(): string;
|
|
54
|
+
/** The rate as a percentage (`"25"` for 0.25), the unit of `taxRate` on the wire. */
|
|
55
|
+
toPercent(): string;
|
|
56
|
+
/** The factor, `"0.25"`. Wire fields say their unit; use `toPercent()` for a `taxRate`. */
|
|
57
|
+
toString(): string;
|
|
58
|
+
toJSON(): string;
|
|
59
|
+
}
|
package/dist/rate.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { divRound, formatUnits, MoneyError, parseDecimal, pow10, trimZeros, } from "./decimal.js";
|
|
2
|
+
/** Most decimals a Rate, Price, FxRate or quantity may be written with. */
|
|
3
|
+
export const MAX_RATE_DECIMALS = 10;
|
|
4
|
+
export const gcd = (a, b) => {
|
|
5
|
+
a = a < 0n ? -a : a;
|
|
6
|
+
b = b < 0n ? -b : b;
|
|
7
|
+
while (b)
|
|
8
|
+
[a, b] = [b, a % b];
|
|
9
|
+
return a;
|
|
10
|
+
};
|
|
11
|
+
/** A decimal string with at most 10 decimals as an exact fraction. */
|
|
12
|
+
export function parseExact(s, what) {
|
|
13
|
+
const { units, scale } = parseDecimal(s, what);
|
|
14
|
+
if (scale > MAX_RATE_DECIMALS)
|
|
15
|
+
throw new MoneyError('too_many_decimals', `A ${what} has at most ${MAX_RATE_DECIMALS} decimals: ${JSON.stringify(s)}`);
|
|
16
|
+
return { num: units, den: pow10(scale) };
|
|
17
|
+
}
|
|
18
|
+
export function parseQuantity(q) {
|
|
19
|
+
if (q instanceof Rate)
|
|
20
|
+
return q;
|
|
21
|
+
if (typeof q === 'string')
|
|
22
|
+
return parseExact(q, 'quantity');
|
|
23
|
+
if (typeof q === 'bigint')
|
|
24
|
+
return { num: q, den: 1n };
|
|
25
|
+
if (typeof q === 'number' && Number.isSafeInteger(q))
|
|
26
|
+
return { num: BigInt(q), den: 1n };
|
|
27
|
+
throw new MoneyError('invalid_decimal', `A quantity is a decimal string or a whole number, never a float: ${String(q)}`);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* A dimensionless rate, kept as an exact factor (a fraction of two bigints): a tax rate, a
|
|
31
|
+
* discount, a proration factor, a ratio. The constructor says the unit: `Rate.percent("25")` and
|
|
32
|
+
* `Rate.factor("0.25")` are the same rate. Up to 10 decimals, sign allowed. Products and quotients
|
|
33
|
+
* of rates lose nothing; a rate is rounded once, where it becomes Money.
|
|
34
|
+
*/
|
|
35
|
+
export class Rate {
|
|
36
|
+
/** Numerator of the factor. */
|
|
37
|
+
num;
|
|
38
|
+
/** Denominator, always positive and in lowest terms with `num`. */
|
|
39
|
+
den;
|
|
40
|
+
constructor(num, den) {
|
|
41
|
+
if (den === 0n)
|
|
42
|
+
throw new MoneyError('division_by_zero', 'A rate cannot have a zero denominator');
|
|
43
|
+
if (den < 0n) {
|
|
44
|
+
num = -num;
|
|
45
|
+
den = -den;
|
|
46
|
+
}
|
|
47
|
+
const g = gcd(num, den) || 1n;
|
|
48
|
+
this.num = num / g;
|
|
49
|
+
this.den = den / g;
|
|
50
|
+
}
|
|
51
|
+
/** A factor: `Rate.factor("0.25")` is a quarter; `Rate.factor(2)` doubles. */
|
|
52
|
+
static factor(v) {
|
|
53
|
+
const { num, den } = parseQuantity(v);
|
|
54
|
+
return new Rate(num, den);
|
|
55
|
+
}
|
|
56
|
+
/** A percentage: `Rate.percent("25")` is the factor 0.25; `"12.5"` is 0.125. */
|
|
57
|
+
static percent(v) {
|
|
58
|
+
const { num, den } = parseQuantity(v);
|
|
59
|
+
return new Rate(num, den * 100n);
|
|
60
|
+
}
|
|
61
|
+
/** The exact quotient `a / b` of two whole numbers or factors (`Rate.ratio(10, 30)` is 1/3). */
|
|
62
|
+
static ratio(a, b) {
|
|
63
|
+
const x = parseQuantity(a);
|
|
64
|
+
const y = parseQuantity(b);
|
|
65
|
+
if (y.num === 0n)
|
|
66
|
+
throw new MoneyError('division_by_zero', 'A ratio over zero');
|
|
67
|
+
return new Rate(x.num * y.den, x.den * y.num);
|
|
68
|
+
}
|
|
69
|
+
/** @internal An exact fraction. */
|
|
70
|
+
static fraction(num, den) {
|
|
71
|
+
return new Rate(num, den);
|
|
72
|
+
}
|
|
73
|
+
multiply(other) {
|
|
74
|
+
return new Rate(this.num * other.num, this.den * other.den);
|
|
75
|
+
}
|
|
76
|
+
divide(other) {
|
|
77
|
+
if (other.num === 0n)
|
|
78
|
+
throw new MoneyError('division_by_zero', 'Division by a zero rate');
|
|
79
|
+
return new Rate(this.num * other.den, this.den * other.num);
|
|
80
|
+
}
|
|
81
|
+
add(other) {
|
|
82
|
+
return new Rate(this.num * other.den + other.num * this.den, this.den * other.den);
|
|
83
|
+
}
|
|
84
|
+
subtract(other) {
|
|
85
|
+
return this.add(other.negate());
|
|
86
|
+
}
|
|
87
|
+
negate() {
|
|
88
|
+
return new Rate(-this.num, this.den);
|
|
89
|
+
}
|
|
90
|
+
isZero() {
|
|
91
|
+
return this.num === 0n;
|
|
92
|
+
}
|
|
93
|
+
isNegative() {
|
|
94
|
+
return this.num < 0n;
|
|
95
|
+
}
|
|
96
|
+
compare(other) {
|
|
97
|
+
const d = this.num * other.den - other.num * this.den;
|
|
98
|
+
return d < 0n ? -1 : d > 0n ? 1 : 0;
|
|
99
|
+
}
|
|
100
|
+
equals(other) {
|
|
101
|
+
return this.compare(other) === 0;
|
|
102
|
+
}
|
|
103
|
+
/** Whether the factor has an exact decimal form with at most `decimals` decimals. */
|
|
104
|
+
isExact(decimals = MAX_RATE_DECIMALS) {
|
|
105
|
+
return (this.num * pow10(decimals)) % this.den === 0n;
|
|
106
|
+
}
|
|
107
|
+
/** The factor with exactly `decimals` decimals, rounded with `mode`. */
|
|
108
|
+
toFixed(decimals, mode) {
|
|
109
|
+
return formatUnits(divRound(this.num * pow10(decimals), this.den, mode), decimals);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The factor as the shortest exact decimal (`"0.25"`). A factor with no exact form within 10
|
|
113
|
+
* decimals (1/3) is shown rounded half-up to 10 decimals; the maths keeps the exact fraction.
|
|
114
|
+
*/
|
|
115
|
+
toFactor() {
|
|
116
|
+
return trimZeros(this.toFixed(MAX_RATE_DECIMALS, 'half-up'));
|
|
117
|
+
}
|
|
118
|
+
/** The rate as a percentage (`"25"` for 0.25), the unit of `taxRate` on the wire. */
|
|
119
|
+
toPercent() {
|
|
120
|
+
return new Rate(this.num * 100n, this.den).toFactor();
|
|
121
|
+
}
|
|
122
|
+
/** The factor, `"0.25"`. Wire fields say their unit; use `toPercent()` for a `taxRate`. */
|
|
123
|
+
toString() {
|
|
124
|
+
return this.toFactor();
|
|
125
|
+
}
|
|
126
|
+
toJSON() {
|
|
127
|
+
return this.toFactor();
|
|
128
|
+
}
|
|
129
|
+
}
|
package/dist/tax.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { RoundingMode } from './decimal.ts';
|
|
2
|
+
import { Money } from './money.ts';
|
|
3
|
+
import type { Rate } from './rate.ts';
|
|
4
|
+
/**
|
|
5
|
+
* The tax on one net amount: `net × rate`, rounded once. The rate is a fraction
|
|
6
|
+
* (`Rate.percent("25")`). Line-level tax is this, called per line.
|
|
7
|
+
*/
|
|
8
|
+
export declare function taxOf(net: Money, rate: Rate, mode: RoundingMode): Money;
|
|
9
|
+
export interface TaxBreakdownLine {
|
|
10
|
+
rate: Rate;
|
|
11
|
+
/** The sum of the net amounts taxed at `rate`. */
|
|
12
|
+
taxable: Money;
|
|
13
|
+
/** The tax at `rate`, rounded once on `taxable`. */
|
|
14
|
+
tax: Money;
|
|
15
|
+
}
|
|
16
|
+
export interface TaxBreakdown {
|
|
17
|
+
lines: TaxBreakdownLine[];
|
|
18
|
+
/** Sum of the taxable amounts. */
|
|
19
|
+
net: Money;
|
|
20
|
+
/** Sum of the per-rate taxes. */
|
|
21
|
+
tax: Money;
|
|
22
|
+
/** `net + tax`. */
|
|
23
|
+
gross: Money;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Document-level tax (EN 16931 style): sums the taxable amount per rate, then rounds the tax once
|
|
27
|
+
* per rate. Lines must share one currency. Sorted by rate, lowest first.
|
|
28
|
+
*/
|
|
29
|
+
export declare function taxByRate(lines: readonly {
|
|
30
|
+
net: Money;
|
|
31
|
+
rate: Rate;
|
|
32
|
+
}[], mode: RoundingMode, currency?: string): TaxBreakdown;
|
package/dist/tax.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { MoneyError } from "./decimal.js";
|
|
2
|
+
import { Money } from "./money.js";
|
|
3
|
+
/**
|
|
4
|
+
* The tax on one net amount: `net × rate`, rounded once. The rate is a fraction
|
|
5
|
+
* (`Rate.percent("25")`). Line-level tax is this, called per line.
|
|
6
|
+
*/
|
|
7
|
+
export function taxOf(net, rate, mode) {
|
|
8
|
+
return net.multiply(rate, mode);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Document-level tax (EN 16931 style): sums the taxable amount per rate, then rounds the tax once
|
|
12
|
+
* per rate. Lines must share one currency. Sorted by rate, lowest first.
|
|
13
|
+
*/
|
|
14
|
+
export function taxByRate(lines, mode, currency) {
|
|
15
|
+
const cur = currency ?? lines[0]?.net.currency;
|
|
16
|
+
if (!cur)
|
|
17
|
+
throw new MoneyError('invalid_money', 'A tax breakdown of no lines needs a currency');
|
|
18
|
+
const groups = new Map();
|
|
19
|
+
for (const l of lines) {
|
|
20
|
+
const rate = l.rate;
|
|
21
|
+
const key = `${rate.num}/${rate.den}`;
|
|
22
|
+
const g = groups.get(key);
|
|
23
|
+
if (g)
|
|
24
|
+
g.taxable = g.taxable.add(l.net);
|
|
25
|
+
else
|
|
26
|
+
groups.set(key, { rate, taxable: Money.zero(cur).add(l.net) });
|
|
27
|
+
}
|
|
28
|
+
const out = [...groups.values()]
|
|
29
|
+
.sort((a, b) => a.rate.compare(b.rate))
|
|
30
|
+
.map((g) => ({ ...g, tax: taxOf(g.taxable, g.rate, mode) }));
|
|
31
|
+
const net = Money.sum(out.map((l) => l.taxable), cur);
|
|
32
|
+
const tax = Money.sum(out.map((l) => l.tax), cur);
|
|
33
|
+
return { lines: out, net, tax, gross: net.add(tax) };
|
|
34
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@newnormal/money",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"description": "One money format, \"NOK 499.00\": ISO 4217 exponents, exact bigint maths with named rounding, allocation, rates, prices, exchange rates and tax. Zero dependencies.",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"money",
|
|
9
|
+
"currency",
|
|
10
|
+
"iso-4217",
|
|
11
|
+
"decimal",
|
|
12
|
+
"bigint",
|
|
13
|
+
"rounding",
|
|
14
|
+
"allocate"
|
|
15
|
+
],
|
|
16
|
+
"homepage": "https://github.com/newnormal-commerce/money#readme",
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/newnormal-commerce/money/issues"
|
|
19
|
+
},
|
|
20
|
+
"repository": "github:newnormal-commerce/money",
|
|
21
|
+
"author": "New Normal Commerce",
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=22",
|
|
25
|
+
"bun": ">=1.2"
|
|
26
|
+
},
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"import": "./dist/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"scripts": {
|
|
39
|
+
"check": "biome check . && tsc -p tsconfig.json",
|
|
40
|
+
"test": "bun test",
|
|
41
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
42
|
+
"prepack": "bun run build"
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"main": "./dist/index.js",
|
|
48
|
+
"types": "./dist/index.d.ts",
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@biomejs/biome": "^2.6.5",
|
|
51
|
+
"@types/bun": "^1.3.0",
|
|
52
|
+
"typescript": "^5.9.3"
|
|
53
|
+
}
|
|
54
|
+
}
|