@ultimat3/money 3.0.0 → 4.0.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/CLAUDE.md CHANGED
@@ -30,7 +30,7 @@ shape is still additive and this is still a minor version.
30
30
  | `arithmetic.ts` | add/subtract/multiply/compare, refuses mixed currencies |
31
31
  | `allocate.ts` | largest-remainder splits that preserve the total |
32
32
  | `factor.ts` | the exact fraction a scaling factor's decimal spelling names. `factorFraction` is internal — never exported; the `Fraction` **type** is public, because `ExchangeRate.ratio` is one |
33
- | `rounding.ts` | explicit modes, no implicit default, over a float (`roundToInteger`) or a ratio (`roundRatio`) |
33
+ | `rounding.ts` | explicit modes, no implicit default, over a float (`roundToInteger`) or a ratio (`roundRatio`, and `roundToDigits` through it) |
34
34
  | `format.ts` | `Intl.NumberFormat` only, digits from the exponent |
35
35
  | `convert.ts` | explicit rate + `RateProvider`, records provenance |
36
36
 
@@ -40,6 +40,12 @@ shape is still additive and this is still a minor version.
40
40
  - Never `/ 100`, and never `exponentOf(amount.currency)` for a value's own precision — that is
41
41
  `moneyScale(amount)`, which falls back to the currency and is right for both. `exponentOf` and
42
42
  `scaleOf` still answer for a *currency*, which is a different question.
43
+ - **A stated currency is an ASSERTION, never a fallback.** `sum(amounts, currency)` used its
44
+ second argument only when the list was empty and ignored it entirely once a first addend existed:
45
+ `sum([money(1, 'EUR')], 'USD')` answered `{ minor: 1, currency: 'EUR' }`, so a caller who wrote
46
+ down USD received EUR with nothing refused — in the one entry point of a file whose header is
47
+ "Integer arithmetic that refuses to mix currencies". A stated currency the first addend
48
+ contradicts is `X_CURRENCY_MISMATCH`.
43
49
  - **Two scales meet at the finer one, never the coarser.** `add`, `subtract` and `compare`
44
50
  widen through `minorAt` (bigint, exact) before they do anything else, so a sub-cent fee added to
45
51
  a cent survives and a comparison answers where storing the widened value would rightly be
@@ -63,7 +69,11 @@ shape is still additive and this is still a minor version.
63
69
  100.49999999999999 `100 * 1.005` produces. A new scaling entry point goes through the same pair
64
70
  — `roundToInteger(a * b, mode)` is the bug, written again. `fromDecimal` was the last float
65
71
  path and it is the one every user-typed price goes through: `Number('0.4999999999999999999')`
66
- is exactly 0.5, so `half-up` saw a tie the written decimal does not have.
72
+ is exactly 0.5, so `half-up` saw a tie the written decimal does not have. **`roundToDigits` was
73
+ that rule broken in this very file** — its body was literally `roundToInteger(value * factor,
74
+ mode) / factor`, so `roundToDigits(1.005, 2, 'half-up')` answered 1.00 where 1.01 is owed. It
75
+ goes through `factorFraction` + `roundRatio` as of 2026-08, and a digit count that is not a whole
76
+ number of decimal places is `X_MONEY_SCALE_INVALID`, never a bare `RangeError` out of `BigInt`.
67
77
  - **`convert` preserves the amount's own `scale`.** `exponentOf(target)` decides the natural scale
68
78
  of a value that names none; a value that names one keeps it, because narrowing $0.000002 to
69
79
  EUR's two decimals is the 10,000x reinterpretation `scale` was added to prevent. Same rule as
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/money",
3
- "version": "3.0.0",
3
+ "version": "4.0.0",
4
4
  "description": "Integer minor units with an attached currency: arithmetic, allocation, rounding, Intl formatting",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -31,7 +31,7 @@
31
31
  "test": "bun test"
32
32
  },
33
33
  "dependencies": {
34
- "@ultimat3/core": "3.0.0",
35
- "@ultimat3/schema": "3.0.0"
34
+ "@ultimat3/core": "4.0.0",
35
+ "@ultimat3/schema": "4.0.0"
36
36
  }
37
37
  }
package/src/arithmetic.ts CHANGED
@@ -39,9 +39,21 @@ export function subtract(left: Money, right: Money): Money {
39
39
  );
40
40
  }
41
41
 
42
- /** Every addend must share one currency; an empty list needs an explicit currency. */
42
+ /**
43
+ * Every addend must share one currency; an empty list needs an explicit currency.
44
+ *
45
+ * A stated currency the first addend contradicts is `X_CURRENCY_MISMATCH`, not a silent win for
46
+ * the list: `sum([money(1, 'EUR')], 'USD')` used to answer `{ minor: 1, currency: 'EUR' }`, so a
47
+ * caller who wrote down USD received EUR and nothing refused — the exact failure this file's
48
+ * header exists to rule out, in the one entry point that treated its currency as a fallback rather
49
+ * than as an assertion.
50
+ */
43
51
  export function sum(amounts: readonly Money[], currency?: string): Money {
44
- const base = amounts[0]?.currency ?? currency;
52
+ const first = amounts[0]?.currency;
53
+ if (first !== undefined && currency !== undefined && first !== currency) {
54
+ throw currencyMismatch(currency, first);
55
+ }
56
+ const base = first ?? currency;
45
57
  if (base === undefined) throw currencyRequired('sum([])');
46
58
  return amounts.reduce((total, amount) => add(total, amount), money(0, base));
47
59
  }
package/src/errors.ts CHANGED
@@ -116,6 +116,19 @@ function countFractionDigits(value: string): number {
116
116
  return value.trim().split('.')[1]?.length ?? 0;
117
117
  }
118
118
 
119
+ /**
120
+ * A `roundToDigits` digit count that names no decimal place. Reported as `X_MONEY_SCALE_INVALID`
121
+ * because a digit count IS a scale — `10 ** 1.5` is not a power of ten, and `BigInt(1.5)` is a
122
+ * bare `RangeError` out of a function whose every other refusal is coded.
123
+ */
124
+ export function digitsInvalid(digits: number): MoneyError {
125
+ return new MoneyError({
126
+ code: 'X_MONEY_SCALE_INVALID',
127
+ cause: `a digit count must be a whole number between -${MAX_MONEY_SCALE} and ${MAX_MONEY_SCALE}, got ${String(digits)}`,
128
+ fix: "pass an integer digit count — roundToDigits(value, 2, 'half-up') for two decimal places",
129
+ });
130
+ }
131
+
119
132
  /** A scale outside 0…MAX_MONEY_SCALE names no decimal place a `minor` could count in. */
120
133
  export function scaleInvalid(scale: number): MoneyError {
121
134
  return new MoneyError({
package/src/rounding.ts CHANGED
@@ -4,7 +4,9 @@
4
4
  */
5
5
 
6
6
  import { invariant } from '@ultimat3/core';
7
- import { notRoundable } from './errors';
7
+ import { MAX_MONEY_SCALE } from '@ultimat3/schema';
8
+ import { digitsInvalid, notRoundable } from './errors';
9
+ import { factorFraction } from './factor';
8
10
 
9
11
  export type RoundingMode =
10
12
  /** 0.5 away from zero — the commercial default most invoicing rules specify. */
@@ -103,12 +105,25 @@ export function roundRatio(
103
105
  /**
104
106
  * Round to `digits` decimal places, used when converting a decimal string whose
105
107
  * precision exceeds the currency's minor unit.
108
+ *
109
+ * Over `roundRatio`, never `roundToInteger(value * factor, mode)` — that product is the bug this
110
+ * package documents as forbidden: `1.005 * 100` is 100.49999999999999, so half-up answered 1.00
111
+ * where 1.01 is owed. The value reaches the mode as the exact fraction its shortest round-trip
112
+ * decimal names, which is the same path `multiply` and `convert` already take.
106
113
  */
107
114
  export function roundToDigits(
108
115
  value: number,
109
116
  digits: number,
110
117
  mode: RoundingMode = DEFAULT_ROUNDING,
111
118
  ): number {
112
- const factor = 10 ** digits;
113
- return roundToInteger(value * factor, mode) / factor;
119
+ if (!Number.isInteger(digits) || Math.abs(digits) > MAX_MONEY_SCALE) throw digitsInvalid(digits);
120
+ const { numerator, denominator } = factorFraction(value);
121
+ const scale = 10n ** BigInt(Math.abs(digits));
122
+ // A negative digit count rounds to tens or hundreds, so the power moves to the other side of the
123
+ // fraction rather than becoming a fractional bigint, which has no spelling.
124
+ const rounded =
125
+ digits >= 0
126
+ ? roundRatio(numerator * scale, denominator, mode)
127
+ : roundRatio(numerator, denominator * scale, mode);
128
+ return digits >= 0 ? rounded / Number(scale) : rounded * Number(scale);
114
129
  }