@vielzeug/coins 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +262 -0
- package/dist/_cache.cjs +2 -0
- package/dist/_cache.cjs.map +1 -0
- package/dist/_cache.d.ts +6 -0
- package/dist/_cache.d.ts.map +1 -0
- package/dist/_cache.js +14 -0
- package/dist/_cache.js.map +1 -0
- package/dist/_dev.cjs +2 -0
- package/dist/_dev.cjs.map +1 -0
- package/dist/_dev.d.ts +2 -0
- package/dist/_dev.d.ts.map +1 -0
- package/dist/_dev.js +9 -0
- package/dist/_dev.js.map +1 -0
- package/dist/coins.cjs +2 -0
- package/dist/coins.cjs.map +1 -0
- package/dist/coins.iife.js +2 -0
- package/dist/coins.iife.js.map +1 -0
- package/dist/coins.js +2 -0
- package/dist/coins.js.map +1 -0
- package/dist/errors.cjs +2 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.ts +52 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -0
- package/dist/exchange.cjs +2 -0
- package/dist/exchange.cjs.map +1 -0
- package/dist/exchange.d.ts +28 -0
- package/dist/exchange.d.ts.map +1 -0
- package/dist/exchange.js +18 -0
- package/dist/exchange.js.map +1 -0
- package/dist/format.cjs +2 -0
- package/dist/format.cjs.map +1 -0
- package/dist/format.d.ts +41 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/format.js +104 -0
- package/dist/format.js.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/money.cjs +2 -0
- package/dist/money.cjs.map +1 -0
- package/dist/money.d.ts +247 -0
- package/dist/money.d.ts.map +1 -0
- package/dist/money.js +208 -0
- package/dist/money.js.map +1 -0
- package/dist/types.d.ts +60 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils.cjs +2 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.d.ts +66 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +66 -0
- package/dist/utils.js.map +1 -0
- package/package.json +39 -0
package/dist/format.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { CoinsError as e } from "./errors.js";
|
|
2
|
+
import { boundedCache as t } from "./_cache.js";
|
|
3
|
+
import { applyRounding as n, getCurrencyDecimals as r, pow10 as i } from "./utils.js";
|
|
4
|
+
//#region src/format.ts
|
|
5
|
+
var a = t(512), o = t(32);
|
|
6
|
+
function s(t, n) {
|
|
7
|
+
let { locale: a = "en-US", maximumFractionDigits: o, minimumFractionDigits: s, style: c = "symbol" } = n, l = r(t.currency), h = u("maximumFractionDigits", o, l), g = u("minimumFractionDigits", s, Math.min(l, h));
|
|
8
|
+
if (g > h) throw new e("minimumFractionDigits must be less than or equal to maximumFractionDigits");
|
|
9
|
+
let _ = d(t.amount, l, h), v = _ < 0n, y = v ? -_ : _, b = i(h), x = y / b, S = f(h === 0 ? "" : (y % b).toString().padStart(h, "0"), g), C = p(a, t.currency, c, v);
|
|
10
|
+
return {
|
|
11
|
+
frac: S,
|
|
12
|
+
intStr: m(a).format(x),
|
|
13
|
+
negative: v,
|
|
14
|
+
template: C
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function c(e, t = {}) {
|
|
18
|
+
return l(e, t).map((e) => e.value).join("");
|
|
19
|
+
}
|
|
20
|
+
function l(e, t = {}) {
|
|
21
|
+
let { frac: n, intStr: r, template: i } = s(e, t), a = n.length > 0, o = [], c = !1;
|
|
22
|
+
for (let e of i) if (e.type !== "group") {
|
|
23
|
+
if (e.type === "integer") {
|
|
24
|
+
c ||= (o.push({
|
|
25
|
+
type: "integer",
|
|
26
|
+
value: r
|
|
27
|
+
}), !0);
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (e.type === "decimal") {
|
|
31
|
+
a && o.push({
|
|
32
|
+
type: "decimal",
|
|
33
|
+
value: e.value
|
|
34
|
+
});
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (e.type === "fraction") {
|
|
38
|
+
a && o.push({
|
|
39
|
+
type: "fraction",
|
|
40
|
+
value: n
|
|
41
|
+
});
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
e.type === "currency" ? o.push({
|
|
45
|
+
type: "currency",
|
|
46
|
+
value: e.value
|
|
47
|
+
}) : e.type === "minusSign" ? o.push({
|
|
48
|
+
type: "minusSign",
|
|
49
|
+
value: e.value
|
|
50
|
+
}) : o.push({
|
|
51
|
+
type: "literal",
|
|
52
|
+
value: e.value
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return o;
|
|
56
|
+
}
|
|
57
|
+
function u(t, n, r) {
|
|
58
|
+
if (n == null) return r;
|
|
59
|
+
if (!Number.isInteger(n) || n < 0) throw new e(`${t} must be a non-negative integer`);
|
|
60
|
+
return n;
|
|
61
|
+
}
|
|
62
|
+
function d(e, t, r) {
|
|
63
|
+
if (t === r) return e;
|
|
64
|
+
if (r > t) return e * i(r - t);
|
|
65
|
+
let a = e < 0n, o = a ? -e : e, s = i(t - r), c = n(o / s, o % s, s, "half-away-from-zero");
|
|
66
|
+
return a ? -c : c;
|
|
67
|
+
}
|
|
68
|
+
function f(e, t) {
|
|
69
|
+
if (e.length === 0) return "";
|
|
70
|
+
let n = e.length;
|
|
71
|
+
for (; n > t && e[n - 1] === "0";) n--;
|
|
72
|
+
return e.slice(0, n);
|
|
73
|
+
}
|
|
74
|
+
function p(e, t, n, r) {
|
|
75
|
+
let i = [
|
|
76
|
+
e,
|
|
77
|
+
t,
|
|
78
|
+
n,
|
|
79
|
+
r ? "neg" : "pos"
|
|
80
|
+
].join("\0"), o = a.get(i);
|
|
81
|
+
if (o !== void 0) return o;
|
|
82
|
+
let s = new Intl.NumberFormat(e, {
|
|
83
|
+
currency: t,
|
|
84
|
+
currencyDisplay: n,
|
|
85
|
+
maximumFractionDigits: 1,
|
|
86
|
+
minimumFractionDigits: 1,
|
|
87
|
+
style: "currency"
|
|
88
|
+
}).formatToParts(r ? -1.1 : 1.1);
|
|
89
|
+
return a.set(i, s), s;
|
|
90
|
+
}
|
|
91
|
+
function m(e) {
|
|
92
|
+
let t = o.get(e);
|
|
93
|
+
if (t !== void 0) return t;
|
|
94
|
+
let n = new Intl.NumberFormat(e, {
|
|
95
|
+
maximumFractionDigits: 0,
|
|
96
|
+
minimumFractionDigits: 0,
|
|
97
|
+
useGrouping: !0
|
|
98
|
+
});
|
|
99
|
+
return o.set(e, n), n;
|
|
100
|
+
}
|
|
101
|
+
//#endregion
|
|
102
|
+
export { c as format, l as formatParts };
|
|
103
|
+
|
|
104
|
+
//# sourceMappingURL=format.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"format.js","names":[],"sources":["../src/format.ts"],"sourcesContent":["import type { FormatOptions, Money, MoneyFormatPart } from './types';\n\nimport { boundedCache } from './_cache';\nimport { CoinsError } from './errors';\nimport { applyRounding, getCurrencyDecimals, pow10 } from './utils';\n\n// Template cache key: locale × currency × style × sign — 512 prevents thrashing in multi-locale apps.\nconst currencyTemplateCache = boundedCache<string, Intl.NumberFormatPart[]>(512);\n// Locale-only key — 32 covers virtually every realistic multi-locale deployment.\nconst integerFormatterCache = boundedCache<string, Intl.NumberFormat>(32);\n\n/**\n * Resolves and validates all formatting parameters, performs scaling, and\n * produces the pre-computed strings shared by `format()` and `formatParts()`.\n * Throws on invalid options. New options only need to be added in one place.\n */\ntype FormatState = {\n frac: string;\n intStr: string;\n negative: boolean;\n template: Intl.NumberFormatPart[];\n};\n\nfunction resolveFormatState(m: Money, options: FormatOptions): FormatState {\n const { locale = 'en-US', maximumFractionDigits, minimumFractionDigits, style = 'symbol' } = options;\n\n const decimalPlaces = getCurrencyDecimals(m.currency);\n const maxFrac = validateFractionDigits('maximumFractionDigits', maximumFractionDigits, decimalPlaces);\n const minFrac = validateFractionDigits(\n 'minimumFractionDigits',\n minimumFractionDigits,\n Math.min(decimalPlaces, maxFrac),\n );\n\n if (minFrac > maxFrac) {\n throw new CoinsError('minimumFractionDigits must be less than or equal to maximumFractionDigits');\n }\n\n const scaled = rescaleMinorUnits(m.amount, decimalPlaces, maxFrac);\n const negative = scaled < 0n;\n const abs = negative ? -scaled : scaled;\n const divisor = pow10(maxFrac);\n const whole = abs / divisor;\n const rawFrac = maxFrac === 0 ? '' : (abs % divisor).toString().padStart(maxFrac, '0');\n const frac = trimFraction(rawFrac, minFrac);\n const template = getCurrencyTemplate(locale, m.currency, style, negative);\n const intStr = getIntegerFormatter(locale).format(whole);\n\n return { frac, intStr, negative, template };\n}\n\n/**\n * Formats a `Money` value as a locale-aware currency string.\n * Uses bigint arithmetic throughout — no floating-point precision loss.\n *\n * When `maximumFractionDigits` is less than the currency's native decimal\n * places, the amount is rescaled using `'half-away-from-zero'` rounding.\n *\n * @example\n * ```ts\n * const price = money('1234.56', 'USD');\n *\n * format(price) // '$1,234.56'\n * format(price, { locale: 'de-DE' }) // '1.234,56 $'\n * format(price, { style: 'code' }) // 'USD 1,234.56'\n * format(price, { style: 'name' }) // '1,234.56 US dollars'\n * ```\n */\nexport function format(m: Money, options: FormatOptions = {}): string {\n return formatParts(m, options)\n .map((p) => p.value)\n .join('');\n}\n\n/**\n * Returns the formatted parts of a `Money` value as a structured array.\n * Useful for custom rendering — apply different styles to each semantic segment\n * (currency symbol, integer, decimal separator, fraction, sign).\n *\n * Joining all `value` fields produces the same string as `format()`.\n * When `maximumFractionDigits` reduces precision, rescaling uses\n * `'half-away-from-zero'` rounding.\n *\n * @example\n * ```ts\n * formatParts(money('1234.56', 'USD'))\n * // [\n * // { type: 'currency', value: '$' },\n * // { type: 'integer', value: '1,234' },\n * // { type: 'decimal', value: '.' },\n * // { type: 'fraction', value: '56' },\n * // ]\n * ```\n */\nexport function formatParts(m: Money, options: FormatOptions = {}): MoneyFormatPart[] {\n const { frac, intStr, template } = resolveFormatState(m, options);\n const hasFrac = frac.length > 0;\n const parts: MoneyFormatPart[] = [];\n let replacedInteger = false;\n\n for (const part of template) {\n // Group separators (e.g. comma in '1,234') are already embedded in intStr by\n // getIntegerFormatter(), so the template's group parts are intentionally discarded.\n if (part.type === 'group') continue;\n\n if (part.type === 'integer') {\n if (!replacedInteger) {\n parts.push({ type: 'integer', value: intStr });\n replacedInteger = true;\n }\n\n continue;\n }\n\n if (part.type === 'decimal') {\n if (hasFrac) parts.push({ type: 'decimal', value: part.value });\n\n continue;\n }\n\n if (part.type === 'fraction') {\n if (hasFrac) parts.push({ type: 'fraction', value: frac });\n\n continue;\n }\n\n if (part.type === 'currency') {\n parts.push({ type: 'currency', value: part.value });\n } else if (part.type === 'minusSign') {\n parts.push({ type: 'minusSign', value: part.value });\n } else {\n parts.push({ type: 'literal', value: part.value });\n }\n }\n\n return parts;\n}\n\nfunction validateFractionDigits(name: string, value: number | undefined, fallback: number): number {\n if (value == null) return fallback;\n\n if (!Number.isInteger(value) || value < 0) {\n throw new CoinsError(`${name} must be a non-negative integer`);\n }\n\n return value;\n}\n\n/**\n * Rescales minor units from `sourceFrac` decimal places to `targetFrac`,\n * using half-away-from-zero rounding when reducing precision.\n * Always normalizes to absolute value before rounding and reapplies the sign after.\n */\nfunction rescaleMinorUnits(amount: bigint, sourceFrac: number, targetFrac: number): bigint {\n if (sourceFrac === targetFrac) return amount;\n\n if (targetFrac > sourceFrac) return amount * pow10(targetFrac - sourceFrac);\n\n const negative = amount < 0n;\n const abs = negative ? -amount : amount;\n const factor = pow10(sourceFrac - targetFrac);\n const quotient = abs / factor;\n const result = applyRounding(quotient, abs % factor, factor, 'half-away-from-zero');\n\n return negative ? -result : result;\n}\n\nfunction trimFraction(value: string, minDigits: number): string {\n if (value.length === 0) return '';\n\n let end = value.length;\n\n while (end > minDigits && value[end - 1] === '0') end--;\n\n return value.slice(0, end);\n}\n\nfunction getCurrencyTemplate(\n locale: string,\n currencyCode: string,\n style: NonNullable<FormatOptions['style']>,\n negative: boolean,\n): Intl.NumberFormatPart[] {\n const key = [locale, currencyCode, style, negative ? 'neg' : 'pos'].join('\\0');\n const cached = currencyTemplateCache.get(key);\n\n if (cached !== undefined) return cached;\n\n const formatter = new Intl.NumberFormat(locale, {\n currency: currencyCode,\n currencyDisplay: style,\n maximumFractionDigits: 1,\n minimumFractionDigits: 1,\n style: 'currency',\n });\n\n const template = formatter.formatToParts(negative ? -1.1 : 1.1);\n\n currencyTemplateCache.set(key, template);\n\n return template;\n}\n\nfunction getIntegerFormatter(locale: string): Intl.NumberFormat {\n const cached = integerFormatterCache.get(locale);\n\n if (cached !== undefined) return cached;\n\n const formatter = new Intl.NumberFormat(locale, {\n maximumFractionDigits: 0,\n minimumFractionDigits: 0,\n useGrouping: true,\n });\n\n integerFormatterCache.set(locale, formatter);\n\n return formatter;\n}\n"],"mappings":";;;;AAOA,IAAM,IAAwB,EAA8C,GAAG,GAEzE,IAAwB,EAAwC,EAAE;AAcxE,SAAS,EAAmB,GAAU,GAAqC;CACzE,IAAM,EAAE,YAAS,SAAS,0BAAuB,0BAAuB,WAAQ,aAAa,GAEvF,IAAgB,EAAoB,EAAE,QAAQ,GAC9C,IAAU,EAAuB,yBAAyB,GAAuB,CAAa,GAC9F,IAAU,EACd,yBACA,GACA,KAAK,IAAI,GAAe,CAAO,CACjC;CAEA,IAAI,IAAU,GACZ,MAAM,IAAI,EAAW,2EAA2E;CAGlG,IAAM,IAAS,EAAkB,EAAE,QAAQ,GAAe,CAAO,GAC3D,IAAW,IAAS,IACpB,IAAM,IAAW,CAAC,IAAS,GAC3B,IAAU,EAAM,CAAO,GACvB,IAAQ,IAAM,GAEd,IAAO,EADG,MAAY,IAAI,MAAM,IAAM,EAAA,CAAS,SAAS,CAAC,CAAC,SAAS,GAAS,GAAG,GAClD,CAAO,GACpC,IAAW,EAAoB,GAAQ,EAAE,UAAU,GAAO,CAAQ;CAGxE,OAAO;EAAE;EAAM,QAFA,EAAoB,CAAM,CAAC,CAAC,OAAO,CAEnC;EAAQ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Aa,GAAY,OAAO,IAAS,EAAM,IAAa,CAAU;CAE1E,IAAM,IAAW,IAAS,IACpB,IAAM,IAAW,CAAC,IAAS,GAC3B,IAAS,EAAM,IAAa,CAAU,GAEtC,IAAS,EADE,IAAM,GACgB,IAAM,GAAQ,GAAQ,qBAAqB;CAElF,OAAO,IAAW,CAAC,IAAS;AAC9B;AAEA,SAAS,EAAa,GAAe,GAA2B;CAC9D,IAAI,EAAM,WAAW,GAAG,OAAO;CAE/B,IAAI,IAAM,EAAM;CAEhB,OAAO,IAAM,KAAa,EAAM,IAAM,OAAO,MAAK;CAElD,OAAO,EAAM,MAAM,GAAG,CAAG;AAC3B;AAEA,SAAS,EACP,GACA,GACA,GACA,GACyB;CACzB,IAAM,IAAM;EAAC;EAAQ;EAAc;EAAO,IAAW,QAAQ;CAAK,CAAC,CAAC,KAAK,IAAI,GACvE,IAAS,EAAsB,IAAI,CAAG;CAE5C,IAAI,MAAW,KAAA,GAAW,OAAO;CAUjC,IAAM,IAAW,IARK,KAAK,aAAa,GAAQ;EAC9C,UAAU;EACV,iBAAiB;EACjB,uBAAuB;EACvB,uBAAuB;EACvB,OAAO;CACT,CAEiB,CAAA,CAAU,cAAc,IAAW,OAAO,GAAG;CAI9D,OAFA,EAAsB,IAAI,GAAK,CAAQ,GAEhC;AACT;AAEA,SAAS,EAAoB,GAAmC;CAC9D,IAAM,IAAS,EAAsB,IAAI,CAAM;CAE/C,IAAI,MAAW,KAAA,GAAW,OAAO;CAEjC,IAAM,IAAY,IAAI,KAAK,aAAa,GAAQ;EAC9C,uBAAuB;EACvB,uBAAuB;EACvB,aAAa;CACf,CAAC;CAID,OAFA,EAAsB,IAAI,GAAQ,CAAS,GAEpC;AACT"}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./utils.cjs"),n=require("./exchange.cjs"),r=require("./format.cjs"),i=require("./money.cjs");exports.CoinsError=e.CoinsError,exports.CurrencyMismatchError=e.CurrencyMismatchError,exports.InvalidCurrencyError=e.InvalidCurrencyError,exports.abs=i.abs,exports.add=i.add,exports.allocate=i.allocate,exports.clamp=i.clamp,exports.compare=i.compare,exports.divide=i.divide,exports.exchange=n.exchange,exports.format=r.format,exports.formatParts=r.formatParts,exports.fromJSON=i.fromJSON,exports.getCurrencyDecimals=t.getCurrencyDecimals,exports.greaterThan=i.greaterThan,exports.greaterThanOrEqual=i.greaterThanOrEqual,exports.isEqual=i.isEqual,exports.isMoney=i.isMoney,exports.isNegative=i.isNegative,exports.isNonNegative=i.isNonNegative,exports.isNonPositive=i.isNonPositive,exports.isPositive=i.isPositive,exports.isZero=i.isZero,exports.lessThan=i.lessThan,exports.lessThanOrEqual=i.lessThanOrEqual,exports.max=i.max,exports.min=i.min,exports.money=i.money,exports.multiply=i.multiply,exports.negate=i.negate,exports.roundTo=i.roundTo,exports.splitEvenly=i.splitEvenly,exports.subtract=i.subtract,exports.sum=i.sum,exports.toDecimal=i.toDecimal,exports.toJSON=i.toJSON,exports.toNumber=i.toNumber,exports.validateCurrencyCode=t.validateCurrencyCode,exports.withAmount=i.withAmount;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { CoinsError, CurrencyMismatchError, InvalidCurrencyError } from './errors';
|
|
2
|
+
export { exchange } from './exchange';
|
|
3
|
+
export { format, formatParts } from './format';
|
|
4
|
+
export { getCurrencyDecimals, validateCurrencyCode } from './utils';
|
|
5
|
+
export { abs, add, allocate, clamp, compare, divide, fromJSON, greaterThan, greaterThanOrEqual, isEqual, isMoney, isNegative, isNonNegative, isNonPositive, isPositive, isZero, lessThan, lessThanOrEqual, max, min, money, multiply, negate, roundTo, splitEvenly, subtract, sum, toDecimal, toJSON, toNumber, withAmount, } from './money';
|
|
6
|
+
export type { CurrencyCode, ExchangeRate, FormatOptions, Money, MoneyFormatPart, MoneyJSON, RoundingMode, } from './types';
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AACnF,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAC/C,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AACpE,OAAO,EACL,GAAG,EACH,GAAG,EACH,QAAQ,EACR,KAAK,EACL,OAAO,EACP,MAAM,EACN,QAAQ,EACR,WAAW,EACX,kBAAkB,EAClB,OAAO,EACP,OAAO,EACP,UAAU,EACV,aAAa,EACb,aAAa,EACb,UAAU,EACV,MAAM,EACN,QAAQ,EACR,eAAe,EACf,GAAG,EACH,GAAG,EACH,KAAK,EACL,QAAQ,EACR,MAAM,EACN,OAAO,EACP,WAAW,EACX,QAAQ,EACR,GAAG,EACH,SAAS,EACT,MAAM,EACN,QAAQ,EACR,UAAU,GACX,MAAM,SAAS,CAAC;AACjB,YAAY,EACV,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,KAAK,EACL,eAAe,EACf,SAAS,EACT,YAAY,GACb,MAAM,SAAS,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { CoinsError as e, CurrencyMismatchError as t, InvalidCurrencyError as n } from "./errors.js";
|
|
2
|
+
import { getCurrencyDecimals as r, validateCurrencyCode as i } from "./utils.js";
|
|
3
|
+
import { exchange as a } from "./exchange.js";
|
|
4
|
+
import { format as o, formatParts as s } from "./format.js";
|
|
5
|
+
import { abs as c, add as l, allocate as u, clamp as d, compare as f, divide as p, fromJSON as m, greaterThan as h, greaterThanOrEqual as g, isEqual as _, isMoney as v, isNegative as y, isNonNegative as b, isNonPositive as x, isPositive as S, isZero as C, lessThan as w, lessThanOrEqual as T, max as E, min as D, money as O, multiply as k, negate as A, roundTo as j, splitEvenly as M, subtract as N, sum as P, toDecimal as F, toJSON as I, toNumber as L, withAmount as R } from "./money.js";
|
|
6
|
+
export { e as CoinsError, t as CurrencyMismatchError, n as InvalidCurrencyError, c as abs, l as add, u as allocate, d as clamp, f as compare, p as divide, a as exchange, o as format, s as formatParts, m as fromJSON, r as getCurrencyDecimals, h as greaterThan, g as greaterThanOrEqual, _ as isEqual, v as isMoney, y as isNegative, b as isNonNegative, x as isNonPositive, S as isPositive, C as isZero, w as lessThan, T as lessThanOrEqual, E as max, D as min, O as money, k as multiply, A as negate, j as roundTo, M as splitEvenly, N as subtract, P as sum, F as toDecimal, I as toJSON, L as toNumber, i as validateCurrencyCode, R as withAmount };
|
package/dist/money.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./errors.cjs"),t=require("./utils.cjs"),n=require("./_dev.cjs");function r(e,r){let i=t.validateCurrencyCode(r);if(typeof e==`bigint`)return{amount:e,currency:i};if(typeof e==`number`){let r=t.getCurrencyDecimals(i),o=String(e),s=t.SCIENTIFIC_RE.test(o)?t.expandScientific(o):o,c=s.indexOf(`.`),l=c===-1?0:s.length-c-1;return l>r&&n.warn(`money(): number input "${e}" has more decimal places (${l}) than ${i} supports (${r}). Use a decimal string to avoid IEEE-754 precision loss.`),{amount:a(o,r),currency:i}}return{amount:a(String(e),t.getCurrencyDecimals(i)),currency:i}}function i(t,n){if(t.currency!==n.currency)throw new e.CurrencyMismatchError(t.currency,n.currency)}function a(e,n){let{denominator:r,negative:i,numerator:a}=t.parseRational(e),o=a*t.pow10(n),s=t.applyRounding(o/r,o%r,r,`half-away-from-zero`);return i?-s:s}function o(e,t){return{amount:t,currency:e.currency}}function s(e){if(typeof e!=`object`||!e)return!1;let t=e;return Object.hasOwn(t,`amount`)&&typeof t.amount==`bigint`&&Object.hasOwn(t,`currency`)&&typeof t.currency==`string`}function c(e,t){return i(e,t),{amount:e.amount+t.amount,currency:e.currency}}function l(e,t){return i(e,t),{amount:e.amount-t.amount,currency:e.currency}}function u(e,n,r=`half-away-from-zero`){let{denominator:i,negative:a,numerator:o}=t.parseRational(String(n)),s=e.amount<0n!==a,c=(e.amount<0n?-e.amount:e.amount)*o,l=t.applyRounding(c/i,c%i,i,r,s);return{amount:s?-l:l,currency:e.currency}}function d(n,r,i=`half-away-from-zero`){let{denominator:a,negative:o,numerator:s}=t.parseRational(String(r));if(s===0n)throw new e.CoinsError(`Division by zero`);let c=n.amount<0n!==o,l=(n.amount<0n?-n.amount:n.amount)*a,u=t.applyRounding(l/s,l%s,s,i,c);return{amount:c?-u:u,currency:n.currency}}function f(n,r){if(r.length===0)throw new e.CoinsError(`allocate requires at least one ratio`);let i=r.map(e=>t.parseRational(String(e)));if(i.some(e=>e.negative))throw new e.CoinsError(`All ratios must be non-negative`);if(!i.some(e=>e.numerator>0n))throw new e.CoinsError(`At least one ratio must be positive`);let a=n.amount<0n,o=a?-n.amount:n.amount,s=i.reduce((e,t)=>t.denominator>e?t.denominator:e,1n),c=i.map(e=>e.numerator*(s/e.denominator)),l=c.reduce((e,t)=>e+t,0n),u=[],d=[];for(let e of c){let t=o*e;u.push(t/l),d.push(t%l)}let f=r.map((e,t)=>t).sort((e,t)=>{let n=d[t]-d[e];return n>0n?1:n<0n?-1:0}),p=[...u],m=o-u.reduce((e,t)=>e+t,0n);for(let e=0;m>0n;e++,m--)p[f[e]]+=1n;return p.map(e=>({amount:a?-e:e,currency:n.currency}))}function p(t){if(t.length===0)throw new e.CoinsError(`sum requires at least one Money value`);let n=t[0].currency;for(let r=1;r<t.length;r++)if(t[r].currency!==n)throw new e.CurrencyMismatchError(n,t[r].currency);return{amount:t.reduce((e,t)=>e+t.amount,0n),currency:n}}function m(t){if(t.length===0)throw new e.CoinsError(`min requires at least one Money value`);let n=t[0];for(let e=1;e<t.length;e++)n=b(n,t[e])<=0?n:t[e];return n}function h(t){if(t.length===0)throw new e.CoinsError(`max requires at least one Money value`);let n=t[0];for(let e=1;e<t.length;e++)n=b(n,t[e])>=0?n:t[e];return n}function g(t,n){if(!Number.isInteger(n)||n<=0)throw new e.CoinsError(`splitEvenly requires a positive integer number of parts`);return f(t,Array.from({length:n},()=>1))}function _(t,n,r){if(t.currency!==n.currency||t.currency!==r.currency)throw new e.CurrencyMismatchError(t.currency,t.currency===n.currency?r.currency:n.currency);if(b(n,r)>0)throw new e.CoinsError(`clamp: lower (${N(n)} ${n.currency}) must be <= upper (${N(r)} ${r.currency})`);return h([n,m([t,r])])}function v(e){return{amount:e.amount<0n?-e.amount:e.amount,currency:e.currency}}function y(e){return{amount:-e.amount,currency:e.currency}}function b(e,t){return i(e,t),e.amount<t.amount?-1:+(e.amount>t.amount)}function x(e,t){return e.currency===t.currency&&e.amount===t.amount}function S(e,t){return b(e,t)>0}function C(e,t){return b(e,t)>=0}function w(e,t){return b(e,t)<0}function T(e,t){return b(e,t)<=0}function E(e){return e.amount===0n}function D(e){return e.amount>0n}function O(e){return e.amount<0n}function k(e){return e.amount>=0n}function A(e){return e.amount<=0n}function j(e){return{amount:String(e.amount),currency:e.currency}}function M(n){let r=t.validateCurrencyCode(n.currency);if(typeof n.amount!=`string`)throw new e.CoinsError(`Invalid money amount in JSON: ${String(n.amount)} (expected an integer string, e.g. '123456')`);let i;try{i=BigInt(n.amount)}catch{throw new e.CoinsError(`Invalid money amount in JSON: "${n.amount}" (expected an integer string, e.g. '123456')`)}return{amount:i,currency:r}}function N(e){let n=t.getCurrencyDecimals(e.currency);if(n===0)return String(e.amount);let r=e.amount<0n,i=r?-e.amount:e.amount,a=t.pow10(n),o=i/a,s=(i%a).toString().padStart(n,`0`);return`${r?`-`:``}${o}.${s}`}function P(e){let n=t.getCurrencyDecimals(e.currency);return Number(e.amount)/Number(t.pow10(n))}function F(n,r,i=`half-away-from-zero`){if(!Number.isInteger(r)||r<0)throw new e.CoinsError(`roundTo: places must be a non-negative integer, got ${r}`);let a=t.getCurrencyDecimals(n.currency);if(r>a)throw new e.CoinsError(`roundTo: places (${r}) exceeds the decimal places for ${n.currency} (${a})`);if(r===a)return n;let o=t.pow10(a-r),s=n.amount<0n,c=s?-n.amount:n.amount,l=t.applyRounding(c/o,c%o,o,i,s);return{amount:s?-l:l,currency:n.currency}}exports.abs=v,exports.add=c,exports.allocate=f,exports.clamp=_,exports.compare=b,exports.divide=d,exports.fromJSON=M,exports.greaterThan=S,exports.greaterThanOrEqual=C,exports.isEqual=x,exports.isMoney=s,exports.isNegative=O,exports.isNonNegative=k,exports.isNonPositive=A,exports.isPositive=D,exports.isZero=E,exports.lessThan=w,exports.lessThanOrEqual=T,exports.max=h,exports.min=m,exports.money=r,exports.multiply=u,exports.negate=y,exports.roundTo=F,exports.splitEvenly=g,exports.subtract=l,exports.sum=p,exports.toDecimal=N,exports.toJSON=j,exports.toNumber=P,exports.withAmount=o;
|
|
2
|
+
//# sourceMappingURL=money.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"money.cjs","names":[],"sources":["../src/money.ts"],"sourcesContent":["import type { CurrencyCode, Money, MoneyJSON, RoundingMode } from './types';\n\nimport { warn } from './_dev';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport {\n applyRounding,\n expandScientific,\n getCurrencyDecimals,\n parseRational,\n pow10,\n SCIENTIFIC_RE,\n validateCurrencyCode,\n} from './utils';\n\nexport { CoinsError, CurrencyMismatchError, InvalidCurrencyError } from './errors';\n\n// ─── Factories ───────────────────────────────────────────────────────────────\n\n/**\n * Creates a `Money` value from a decimal string, number, or raw bigint minor units.\n * Validates the currency code — throws `InvalidCurrencyError` for unrecognised ISO 4217 codes.\n *\n * - **string** `'1234.56'` → parsed losslessly; respects the currency's decimal places.\n * - **number** `1234.56` → converted via `String()` first; inherits IEEE-754 limits.\n * Prefer strings when precision matters.\n * - **bigint** `123456n` → used as-is (already in minor units).\n *\n * @example\n * ```ts\n * money('1234.56', 'USD') // { amount: 123456n, currency: 'USD' }\n * money(1234, 'JPY') // { amount: 1234n, currency: 'JPY' }\n * money(123456n, 'USD') // { amount: 123456n, currency: 'USD' }\n * ```\n */\nexport function money(amount: bigint | number | string, currency: CurrencyCode): Money {\n const validCurrency = validateCurrencyCode(currency);\n\n if (typeof amount === 'bigint') {\n return { amount, currency: validCurrency };\n }\n\n if (typeof amount === 'number') {\n const decimals = getCurrencyDecimals(validCurrency);\n const str = String(amount);\n // Expand scientific notation (e.g. String(1e-7) === '1e-7') before measuring fraction\n // length — otherwise inputs like 1e-7 report 0 fractional digits and skip the warning\n // below despite having far more precision than the currency supports.\n const normalized = SCIENTIFIC_RE.test(str) ? expandScientific(str) : str;\n const dotIndex = normalized.indexOf('.');\n const fracLen = dotIndex === -1 ? 0 : normalized.length - dotIndex - 1;\n\n if (fracLen > decimals) {\n warn(\n `money(): number input \"${amount}\" has more decimal places (${fracLen}) than ${validCurrency} supports (${decimals}). ` +\n `Use a decimal string to avoid IEEE-754 precision loss.`,\n );\n }\n\n // getCurrencyDecimals is cached from the validateCurrencyCode call above.\n return { amount: parseToMinorUnits(str, decimals), currency: validCurrency };\n }\n\n // getCurrencyDecimals is cached from the validateCurrencyCode call above.\n return { amount: parseToMinorUnits(String(amount), getCurrencyDecimals(validCurrency)), currency: validCurrency };\n}\n\n// ─── Internal ─────────────────────────────────────────────────────────────────\n\nfunction assertSameCurrency(a: Money, b: Money): void {\n if (a.currency !== b.currency) {\n throw new CurrencyMismatchError(a.currency, b.currency);\n }\n}\n\n/**\n * Converts a decimal string to minor units for the given decimal precision.\n * Uses parseRational + applyRounding to share the single rounding implementation.\n */\nfunction parseToMinorUnits(str: string, decimals: number): bigint {\n const { denominator, negative, numerator } = parseRational(str);\n // numerator/denominator × 10^decimals = numerator × 10^decimals / denominator\n const scale = pow10(decimals);\n const raw = numerator * scale;\n const quotient = raw / denominator;\n const result = applyRounding(quotient, raw % denominator, denominator, 'half-away-from-zero');\n\n return negative ? -result : result;\n}\n\n/**\n * Creates a new `Money` value with the given `amount` and the same currency as `m`.\n * Useful when you compute a raw `bigint` amount externally and need to wrap it\n * back into a `Money` value without re-validating the currency.\n *\n * @example\n * ```ts\n * const price = money('9.99', 'USD');\n * withAmount(price, 1999n) // { amount: 1999n, currency: 'USD' }\n * ```\n */\nexport function withAmount(m: Money, amount: bigint): Money {\n return { amount, currency: m.currency };\n}\n\n/**\n * Type guard that returns `true` if `value` is a `Money`-shaped object\n * (has a `bigint` `amount` and a `string` `currency`).\n * Useful for narrowing unknown payloads from APIs or deserialized storage.\n *\n * Note: does **not** validate the currency code — use `money(0n, currency)` or\n * `validateCurrencyCode()` if you also need to confirm it is a recognized ISO 4217 code.\n *\n * @example\n * ```ts\n * isMoney({ amount: 100n, currency: 'USD' }) // true\n * isMoney({ amount: 1.5, currency: 'USD' }) // false\n * isMoney(null) // false\n * ```\n */\nexport function isMoney(value: unknown): value is Money {\n if (typeof value !== 'object' || value === null) return false;\n\n const v = value as Record<string, unknown>;\n\n return (\n Object.hasOwn(v, 'amount') &&\n typeof v.amount === 'bigint' &&\n Object.hasOwn(v, 'currency') &&\n typeof v.currency === 'string'\n );\n}\n\n// ─── Arithmetic ──────────────────────────────────────────────────────────────\n\n/** Adds two `Money` values. Throws if their currencies differ. */\nexport function add(a: Money, b: Money): Money {\n assertSameCurrency(a, b);\n\n return { amount: a.amount + b.amount, currency: a.currency };\n}\n\n/** Subtracts `b` from `a`. Throws if their currencies differ. */\nexport function subtract(a: Money, b: Money): Money {\n assertSameCurrency(a, b);\n\n return { amount: a.amount - b.amount, currency: a.currency };\n}\n\n/**\n * Multiplies a `Money` value by a scalar factor.\n * The factor can be a decimal string (lossless) or a number.\n *\n * @param mode Rounding mode for fractional minor units. Defaults to `'half-away-from-zero'`.\n *\n * @example\n * ```ts\n * multiply(money('100.00', 'USD'), '1.5') // $150.00\n * multiply(money('1.00', 'USD'), '0.339', 'floor') // $0.33\n * multiply(money('1.00', 'USD'), '0.339', 'ceiling') // $0.34\n * ```\n */\nexport function multiply(m: Money, factor: number | string, mode: RoundingMode = 'half-away-from-zero'): Money {\n const { denominator, negative: factorNegative, numerator } = parseRational(String(factor));\n const negative = m.amount < 0n !== factorNegative;\n const absAmount = m.amount < 0n ? -m.amount : m.amount;\n const raw = absAmount * numerator;\n const quotient = raw / denominator;\n const result = applyRounding(quotient, raw % denominator, denominator, mode, negative);\n\n return { amount: negative ? -result : result, currency: m.currency };\n}\n\n/**\n * Divides a `Money` value by a scalar divisor.\n * The divisor can be a decimal string (lossless) or a number.\n *\n * @param mode Rounding mode for fractional minor units. Defaults to `'half-away-from-zero'`.\n * @throws {CoinsError} On division by zero.\n *\n * @example\n * ```ts\n * divide(money('100.00', 'USD'), 3) // $33.33\n * divide(money('100.00', 'USD'), 3, 'ceiling') // $33.34\n * ```\n */\nexport function divide(m: Money, divisor: number | string, mode: RoundingMode = 'half-away-from-zero'): Money {\n const { denominator: parsedDenom, negative: divisorNegative, numerator } = parseRational(String(divisor));\n\n if (numerator === 0n) throw new CoinsError('Division by zero');\n\n const negative = m.amount < 0n !== divisorNegative;\n const absAmount = m.amount < 0n ? -m.amount : m.amount;\n // Dividing by (numerator/parsedDenom) = multiplying by (parsedDenom/numerator).\n const raw = absAmount * parsedDenom;\n const quotient = raw / numerator;\n const result = applyRounding(quotient, raw % numerator, numerator, mode, negative);\n\n return { amount: negative ? -result : result, currency: m.currency };\n}\n\n/**\n * Distributes `money` across `ratios` without losing or gaining a single minor unit.\n * Accepts both number and string ratios — use strings for lossless decimal weights.\n *\n * Uses the Largest Remainder Method: each share gets its floor allocation first,\n * then any remainder units are assigned one-by-one to the shares with the largest\n * fractional parts, breaking ties by original index (stable, left-to-right).\n *\n * Throws if `ratios` is empty, contains negative values (including negative strings like `'-0.5'`), or sums to zero.\n *\n * @example\n * ```ts\n * allocate(money('10.00', 'USD'), [1, 1, 1])\n * // → [$3.34, $3.33, $3.33] (not three × $3.33 — that loses a penny)\n *\n * allocate(money('10.00', 'USD'), ['0.3', '0.7'])\n * // → [$3.00, $7.00]\n * ```\n */\nexport function allocate(m: Money, ratios: readonly (number | string)[]): [Money, ...Money[]] {\n if (ratios.length === 0) throw new CoinsError('allocate requires at least one ratio');\n\n const parsedRatios = ratios.map((r) => parseRational(String(r)));\n\n if (parsedRatios.some((p) => p.negative)) throw new CoinsError('All ratios must be non-negative');\n\n if (!parsedRatios.some((p) => p.numerator > 0n)) throw new CoinsError('At least one ratio must be positive');\n\n const negative = m.amount < 0n;\n const absAmount = negative ? -m.amount : m.amount;\n\n // All denominators are powers of 10; the max is their LCM — use it to normalise weights to integers.\n const maxDenominator = parsedRatios.reduce((max, p) => (p.denominator > max ? p.denominator : max), 1n);\n const bigWeights = parsedRatios.map((p) => p.numerator * (maxDenominator / p.denominator));\n const bigTotal = bigWeights.reduce((a, b) => a + b, 0n);\n\n // Floor allocation + fractional remainders.\n const floors: bigint[] = [];\n const fracRemainders: bigint[] = [];\n\n for (const w of bigWeights) {\n const ideal = absAmount * w;\n\n floors.push(ideal / bigTotal);\n fracRemainders.push(ideal % bigTotal);\n }\n\n // Distribute leftover units to the shares with the largest fractional remainders.\n // Relies on V8/SpiderMonkey's stable sort (ECMAScript 2019+ spec-mandated): ties\n // in fractional remainders are broken by original index (left-to-right), ensuring\n // deterministic output for equal-weight ratios (e.g. [1, 1, 1]).\n const indices = ratios\n .map((_, i) => i)\n .sort((a, b) => {\n const diff = fracRemainders[b]! - fracRemainders[a]!;\n\n return diff > 0n ? 1 : diff < 0n ? -1 : 0;\n });\n\n const result = [...floors];\n // `remaining` is always < ratios.length (at most one unit per share), safe for this loop.\n let remaining = absAmount - floors.reduce((a, b) => a + b, 0n);\n\n for (let i = 0; remaining > 0n; i++, remaining--) {\n result[indices[i]!]! += 1n;\n }\n\n return result.map((amount) => ({ amount: negative ? -amount : amount, currency: m.currency })) as [Money, ...Money[]];\n}\n\n// ─── Aggregates ──────────────────────────────────────────────────────────────\n\n/**\n * Sums an array of `Money` values. Throws if the array is empty or currencies differ.\n *\n * @example\n * ```ts\n * sum([money('1.00', 'USD'), money('2.50', 'USD')]) // $3.50\n * ```\n */\nexport function sum(moneys: readonly Money[]): Money {\n if (moneys.length === 0) throw new CoinsError('sum requires at least one Money value');\n\n const currency = moneys[0]!.currency;\n\n for (let i = 1; i < moneys.length; i++) {\n if (moneys[i]!.currency !== currency) {\n throw new CurrencyMismatchError(currency, moneys[i]!.currency);\n }\n }\n\n return { amount: moneys.reduce((acc, m) => acc + m.amount, 0n), currency };\n}\n\n/**\n * Returns the smallest `Money` value from a non-empty array. Throws if currencies differ.\n *\n * @example\n * ```ts\n * min([money('3.00', 'USD'), money('1.00', 'USD'), money('2.00', 'USD')]) // $1.00\n * ```\n */\nexport function min(moneys: readonly Money[]): Money {\n if (moneys.length === 0) throw new CoinsError('min requires at least one Money value');\n\n let result = moneys[0]!;\n\n for (let i = 1; i < moneys.length; i++) result = compare(result, moneys[i]!) <= 0 ? result : moneys[i]!;\n\n return result;\n}\n\n/**\n * Returns the largest `Money` value from a non-empty array. Throws if currencies differ.\n *\n * @example\n * ```ts\n * max([money('1.00', 'USD'), money('3.00', 'USD'), money('2.00', 'USD')]) // $3.00\n * ```\n */\nexport function max(moneys: readonly Money[]): Money {\n if (moneys.length === 0) throw new CoinsError('max requires at least one Money value');\n\n let result = moneys[0]!;\n\n for (let i = 1; i < moneys.length; i++) result = compare(result, moneys[i]!) >= 0 ? result : moneys[i]!;\n\n return result;\n}\n\n/**\n * Splits `money` into `parts` equal shares without losing or gaining a single minor unit.\n * Equivalent to `allocate(money, Array.from({ length: parts }, () => 1))`.\n *\n * @throws {CoinsError} If `parts` is not a positive integer (≥ 1).\n *\n * @example\n * ```ts\n * splitEvenly(money('10.00', 'USD'), 3)\n * // → [$3.34, $3.33, $3.33]\n * ```\n */\nexport function splitEvenly(m: Money, parts: number): [Money, ...Money[]] {\n if (!Number.isInteger(parts) || parts <= 0) {\n throw new CoinsError('splitEvenly requires a positive integer number of parts');\n }\n\n return allocate(\n m,\n Array.from({ length: parts }, () => 1),\n );\n}\n\n/**\n * Clamps `m` to the inclusive range `[lower, upper]`.\n *\n * @throws {CurrencyMismatchError} If `m`, `lower`, or `upper` have different currencies.\n * @throws {CoinsError} If `lower > upper`.\n *\n * @example\n * ```ts\n * clamp(money('5.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $5.00\n * clamp(money('0.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $1.00\n * clamp(money('15.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $10.00\n * ```\n */\nexport function clamp(m: Money, lower: Money, upper: Money): Money {\n // Validate currency consistency upfront so the error always names the mismatch,\n // rather than surfacing mid-computation from min() or max().\n if (m.currency !== lower.currency || m.currency !== upper.currency) {\n throw new CurrencyMismatchError(m.currency, m.currency !== lower.currency ? lower.currency : upper.currency);\n }\n\n if (compare(lower, upper) > 0) {\n throw new CoinsError(\n `clamp: lower (${toDecimal(lower)} ${lower.currency}) must be <= upper (${toDecimal(upper)} ${upper.currency})`,\n );\n }\n\n return max([lower, min([m, upper])]);\n}\n\n// ─── Unary ───────────────────────────────────────────────────────────────────\n\n/** Returns the absolute value of `money`. Negative amounts become positive. */\nexport function abs(m: Money): Money {\n return { amount: m.amount < 0n ? -m.amount : m.amount, currency: m.currency };\n}\n\n/** Returns `money` with its sign flipped. */\nexport function negate(m: Money): Money {\n return { amount: -m.amount, currency: m.currency };\n}\n\n// ─── Comparison ──────────────────────────────────────────────────────────────\n\n/**\n * Compares two `Money` values. Returns `-1`, `0`, or `1`.\n * Throws if their currencies differ.\n */\nexport function compare(a: Money, b: Money): -1 | 0 | 1 {\n assertSameCurrency(a, b);\n\n if (a.amount < b.amount) return -1;\n\n if (a.amount > b.amount) return 1;\n\n return 0;\n}\n\n/**\n * Returns `true` if both `Money` values have the same currency and amount.\n * Returns `false` if currencies differ — safe to use in `.filter()` and conditional chains.\n */\nexport function isEqual(a: Money, b: Money): boolean {\n return a.currency === b.currency && a.amount === b.amount;\n}\n\n/** Returns `true` if `a` is strictly greater than `b`. Throws on currency mismatch. */\nexport function greaterThan(a: Money, b: Money): boolean {\n return compare(a, b) > 0;\n}\n\n/** Returns `true` if `a` is greater than or equal to `b`. Throws on currency mismatch. */\nexport function greaterThanOrEqual(a: Money, b: Money): boolean {\n return compare(a, b) >= 0;\n}\n\n/** Returns `true` if `a` is strictly less than `b`. Throws on currency mismatch. */\nexport function lessThan(a: Money, b: Money): boolean {\n return compare(a, b) < 0;\n}\n\n/** Returns `true` if `a` is less than or equal to `b`. Throws on currency mismatch. */\nexport function lessThanOrEqual(a: Money, b: Money): boolean {\n return compare(a, b) <= 0;\n}\n\n// ─── Predicates ──────────────────────────────────────────────────────────────\n\n/** Returns `true` if the amount is exactly zero. */\nexport function isZero(m: Money): boolean {\n return m.amount === 0n;\n}\n\n/** Returns `true` if the amount is strictly positive (> 0). */\nexport function isPositive(m: Money): boolean {\n return m.amount > 0n;\n}\n\n/** Returns `true` if the amount is strictly negative (< 0). */\nexport function isNegative(m: Money): boolean {\n return m.amount < 0n;\n}\n\n/** Returns `true` if the amount is zero or positive (>= 0). */\nexport function isNonNegative(m: Money): boolean {\n return m.amount >= 0n;\n}\n\n/** Returns `true` if the amount is zero or negative (<= 0). */\nexport function isNonPositive(m: Money): boolean {\n return m.amount <= 0n;\n}\n\n// ─── Serialization ───────────────────────────────────────────────────────────\n\n/**\n * Serializes a `Money` value to a plain-object JSON-safe form.\n * `amount` is a bigint string (e.g. `'123456'`) to avoid `JSON.stringify` throwing.\n *\n * @example\n * ```ts\n * toJSON(money('1234.56', 'USD')) // { amount: '123456', currency: 'USD' }\n * JSON.stringify(toJSON(price)) // '{\"amount\":\"123456\",\"currency\":\"USD\"}'\n * ```\n */\nexport function toJSON(m: Money): MoneyJSON {\n return { amount: String(m.amount), currency: m.currency };\n}\n\n/**\n * Deserializes a `MoneyJSON` object back into a `Money` value.\n * Validates the currency code and the amount string.\n *\n * @example\n * ```ts\n * fromJSON({ amount: '123456', currency: 'USD' }) // { amount: 123456n, currency: 'USD' }\n * ```\n */\nexport function fromJSON(json: MoneyJSON): Money {\n const validCurrency = validateCurrencyCode(json.currency);\n\n if (typeof json.amount !== 'string') {\n throw new CoinsError(\n `Invalid money amount in JSON: ${String(json.amount)} (expected an integer string, e.g. '123456')`,\n );\n }\n\n let amount: bigint;\n\n try {\n amount = BigInt(json.amount);\n } catch {\n throw new CoinsError(`Invalid money amount in JSON: \"${json.amount}\" (expected an integer string, e.g. '123456')`);\n }\n\n return { amount, currency: validCurrency };\n}\n\n/**\n * Serializes a `Money` value to a decimal string (e.g. `'1234.56'`).\n * Round-trips losslessly with `money()`.\n *\n * @example\n * ```ts\n * toDecimal(money('1234.56', 'USD')) // '1234.56'\n * toDecimal(money(5n, 'USD')) // '0.05'\n * toDecimal(money(1234n, 'JPY')) // '1234'\n * ```\n */\nexport function toDecimal(m: Money): string {\n const decimals = getCurrencyDecimals(m.currency);\n\n if (decimals === 0) return String(m.amount);\n\n const negative = m.amount < 0n;\n const abs = negative ? -m.amount : m.amount;\n const scale = pow10(decimals);\n const whole = abs / scale;\n const frac = (abs % scale).toString().padStart(decimals, '0');\n\n return `${negative ? '-' : ''}${whole}.${frac}`;\n}\n\n/**\n * Converts a `Money` value to a floating-point number.\n * Useful for charting and display; **not** for arithmetic (lossy).\n *\n * @example\n * ```ts\n * toNumber(money('1234.56', 'USD')) // 1234.56\n * ```\n */\nexport function toNumber(m: Money): number {\n const decimals = getCurrencyDecimals(m.currency);\n\n return Number(m.amount) / Number(pow10(decimals));\n}\n\n// ─── Rounding ─────────────────────────────────────────────────────────────────\n\n/**\n * Rounds a `Money` value to fewer decimal places than the currency's default.\n * `places` must be a non-negative integer in the range `0..currencyDecimals`.\n *\n * Useful for display purposes (e.g. rounding USD to whole dollars).\n * @throws {CoinsError} If `places` is out of the allowed range.\n *\n * @param mode Rounding mode. Defaults to `'half-away-from-zero'`.\n *\n * @example\n * ```ts\n * roundTo(money('1234.56', 'USD'), 0) // $1235 (whole dollars)\n * roundTo(money('1234.56', 'USD'), 1) // $1234.6\n * roundTo(money('1234.56', 'USD'), 1, 'floor') // $1234.5\n * roundTo(money('1234', 'JPY'), 0) // ¥1234 (no-op: JPY is already 0-decimal)\n * ```\n */\nexport function roundTo(m: Money, places: number, mode: RoundingMode = 'half-away-from-zero'): Money {\n if (!Number.isInteger(places) || places < 0) {\n throw new CoinsError(`roundTo: places must be a non-negative integer, got ${places}`);\n }\n\n const currencyDecimals = getCurrencyDecimals(m.currency);\n\n if (places > currencyDecimals) {\n throw new CoinsError(\n `roundTo: places (${places}) exceeds the decimal places for ${m.currency} (${currencyDecimals})`,\n );\n }\n\n if (places === currencyDecimals) return m;\n\n const drop = currencyDecimals - places;\n const divisor = pow10(drop);\n const negative = m.amount < 0n;\n const absAmount = negative ? -m.amount : m.amount;\n const quotient = absAmount / divisor;\n const remainder = absAmount % divisor;\n const rounded = applyRounding(quotient, remainder, divisor, mode, negative);\n\n return { amount: negative ? -rounded : rounded, currency: m.currency };\n}\n"],"mappings":"iFAkCA,SAAgB,EAAM,EAAkC,EAA+B,CACrF,IAAM,EAAgB,EAAA,qBAAqB,CAAQ,EAEnD,GAAI,OAAO,GAAW,SACpB,MAAO,CAAE,SAAQ,SAAU,CAAc,EAG3C,GAAI,OAAO,GAAW,SAAU,CAC9B,IAAM,EAAW,EAAA,oBAAoB,CAAa,EAC5C,EAAM,OAAO,CAAM,EAInB,EAAa,EAAA,cAAc,KAAK,CAAG,EAAI,EAAA,iBAAiB,CAAG,EAAI,EAC/D,EAAW,EAAW,QAAQ,GAAG,EACjC,EAAU,IAAa,GAAK,EAAI,EAAW,OAAS,EAAW,EAUrE,OARI,EAAU,GACZ,EAAA,KACE,0BAA0B,EAAO,6BAA6B,EAAQ,SAAS,EAAc,aAAa,EAAS,0DAErH,EAIK,CAAE,OAAQ,EAAkB,EAAK,CAAQ,EAAG,SAAU,CAAc,CAC7E,CAGA,MAAO,CAAE,OAAQ,EAAkB,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AAC,EAAE,OAAS,EAAE,OAC/B,EAAQ,EAAA,MAAM,CAAQ,EACtB,EAAQ,EAAM,EACd,GAAQ,EAAM,EAAA,CAAO,SAAS,CAAC,CAAC,SAAS,EAAU,GAAG,EAE5D,MAAO,GAAG,EAAW,IAAM,KAAK,EAAM,GAAG,GAC3C,CAWA,SAAgB,EAAS,EAAkB,CACzC,IAAM,EAAW,EAAA,oBAAoB,EAAE,QAAQ,EAE/C,OAAO,OAAO,EAAE,MAAM,EAAI,OAAO,EAAA,MAAM,CAAQ,CAAC,CAClD,CAqBA,SAAgB,EAAQ,EAAU,EAAgB,EAAqB,sBAA8B,CACnG,GAAI,CAAC,OAAO,UAAU,CAAM,GAAK,EAAS,EACxC,MAAM,IAAI,EAAA,WAAW,uDAAuD,GAAQ,EAGtF,IAAM,EAAmB,EAAA,oBAAoB,EAAE,QAAQ,EAEvD,GAAI,EAAS,EACX,MAAM,IAAI,EAAA,WACR,oBAAoB,EAAO,mCAAmC,EAAE,SAAS,IAAI,EAAiB,EAChG,EAGF,GAAI,IAAW,EAAkB,OAAO,EAGxC,IAAM,EAAU,EAAA,MADH,EAAmB,CACN,EACpB,EAAW,EAAE,OAAS,GACtB,EAAY,EAAW,CAAC,EAAE,OAAS,EAAE,OAGrC,EAAU,EAAA,cAFC,EAAY,EACX,EAAY,EACqB,EAAS,EAAM,CAAQ,EAE1E,MAAO,CAAE,OAAQ,EAAW,CAAC,EAAU,EAAS,SAAU,EAAE,QAAS,CACvE"}
|
package/dist/money.d.ts
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import type { CurrencyCode, Money, MoneyJSON, RoundingMode } from './types';
|
|
2
|
+
export { CoinsError, CurrencyMismatchError, InvalidCurrencyError } from './errors';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a `Money` value from a decimal string, number, or raw bigint minor units.
|
|
5
|
+
* Validates the currency code — throws `InvalidCurrencyError` for unrecognised ISO 4217 codes.
|
|
6
|
+
*
|
|
7
|
+
* - **string** `'1234.56'` → parsed losslessly; respects the currency's decimal places.
|
|
8
|
+
* - **number** `1234.56` → converted via `String()` first; inherits IEEE-754 limits.
|
|
9
|
+
* Prefer strings when precision matters.
|
|
10
|
+
* - **bigint** `123456n` → used as-is (already in minor units).
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* money('1234.56', 'USD') // { amount: 123456n, currency: 'USD' }
|
|
15
|
+
* money(1234, 'JPY') // { amount: 1234n, currency: 'JPY' }
|
|
16
|
+
* money(123456n, 'USD') // { amount: 123456n, currency: 'USD' }
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export declare function money(amount: bigint | number | string, currency: CurrencyCode): Money;
|
|
20
|
+
/**
|
|
21
|
+
* Creates a new `Money` value with the given `amount` and the same currency as `m`.
|
|
22
|
+
* Useful when you compute a raw `bigint` amount externally and need to wrap it
|
|
23
|
+
* back into a `Money` value without re-validating the currency.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* const price = money('9.99', 'USD');
|
|
28
|
+
* withAmount(price, 1999n) // { amount: 1999n, currency: 'USD' }
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export declare function withAmount(m: Money, amount: bigint): Money;
|
|
32
|
+
/**
|
|
33
|
+
* Type guard that returns `true` if `value` is a `Money`-shaped object
|
|
34
|
+
* (has a `bigint` `amount` and a `string` `currency`).
|
|
35
|
+
* Useful for narrowing unknown payloads from APIs or deserialized storage.
|
|
36
|
+
*
|
|
37
|
+
* Note: does **not** validate the currency code — use `money(0n, currency)` or
|
|
38
|
+
* `validateCurrencyCode()` if you also need to confirm it is a recognized ISO 4217 code.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* isMoney({ amount: 100n, currency: 'USD' }) // true
|
|
43
|
+
* isMoney({ amount: 1.5, currency: 'USD' }) // false
|
|
44
|
+
* isMoney(null) // false
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
export declare function isMoney(value: unknown): value is Money;
|
|
48
|
+
/** Adds two `Money` values. Throws if their currencies differ. */
|
|
49
|
+
export declare function add(a: Money, b: Money): Money;
|
|
50
|
+
/** Subtracts `b` from `a`. Throws if their currencies differ. */
|
|
51
|
+
export declare function subtract(a: Money, b: Money): Money;
|
|
52
|
+
/**
|
|
53
|
+
* Multiplies a `Money` value by a scalar factor.
|
|
54
|
+
* The factor can be a decimal string (lossless) or a number.
|
|
55
|
+
*
|
|
56
|
+
* @param mode Rounding mode for fractional minor units. Defaults to `'half-away-from-zero'`.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```ts
|
|
60
|
+
* multiply(money('100.00', 'USD'), '1.5') // $150.00
|
|
61
|
+
* multiply(money('1.00', 'USD'), '0.339', 'floor') // $0.33
|
|
62
|
+
* multiply(money('1.00', 'USD'), '0.339', 'ceiling') // $0.34
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
export declare function multiply(m: Money, factor: number | string, mode?: RoundingMode): Money;
|
|
66
|
+
/**
|
|
67
|
+
* Divides a `Money` value by a scalar divisor.
|
|
68
|
+
* The divisor can be a decimal string (lossless) or a number.
|
|
69
|
+
*
|
|
70
|
+
* @param mode Rounding mode for fractional minor units. Defaults to `'half-away-from-zero'`.
|
|
71
|
+
* @throws {CoinsError} On division by zero.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* divide(money('100.00', 'USD'), 3) // $33.33
|
|
76
|
+
* divide(money('100.00', 'USD'), 3, 'ceiling') // $33.34
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
export declare function divide(m: Money, divisor: number | string, mode?: RoundingMode): Money;
|
|
80
|
+
/**
|
|
81
|
+
* Distributes `money` across `ratios` without losing or gaining a single minor unit.
|
|
82
|
+
* Accepts both number and string ratios — use strings for lossless decimal weights.
|
|
83
|
+
*
|
|
84
|
+
* Uses the Largest Remainder Method: each share gets its floor allocation first,
|
|
85
|
+
* then any remainder units are assigned one-by-one to the shares with the largest
|
|
86
|
+
* fractional parts, breaking ties by original index (stable, left-to-right).
|
|
87
|
+
*
|
|
88
|
+
* Throws if `ratios` is empty, contains negative values (including negative strings like `'-0.5'`), or sums to zero.
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* ```ts
|
|
92
|
+
* allocate(money('10.00', 'USD'), [1, 1, 1])
|
|
93
|
+
* // → [$3.34, $3.33, $3.33] (not three × $3.33 — that loses a penny)
|
|
94
|
+
*
|
|
95
|
+
* allocate(money('10.00', 'USD'), ['0.3', '0.7'])
|
|
96
|
+
* // → [$3.00, $7.00]
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
export declare function allocate(m: Money, ratios: readonly (number | string)[]): [Money, ...Money[]];
|
|
100
|
+
/**
|
|
101
|
+
* Sums an array of `Money` values. Throws if the array is empty or currencies differ.
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* ```ts
|
|
105
|
+
* sum([money('1.00', 'USD'), money('2.50', 'USD')]) // $3.50
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
export declare function sum(moneys: readonly Money[]): Money;
|
|
109
|
+
/**
|
|
110
|
+
* Returns the smallest `Money` value from a non-empty array. Throws if currencies differ.
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```ts
|
|
114
|
+
* min([money('3.00', 'USD'), money('1.00', 'USD'), money('2.00', 'USD')]) // $1.00
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
export declare function min(moneys: readonly Money[]): Money;
|
|
118
|
+
/**
|
|
119
|
+
* Returns the largest `Money` value from a non-empty array. Throws if currencies differ.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```ts
|
|
123
|
+
* max([money('1.00', 'USD'), money('3.00', 'USD'), money('2.00', 'USD')]) // $3.00
|
|
124
|
+
* ```
|
|
125
|
+
*/
|
|
126
|
+
export declare function max(moneys: readonly Money[]): Money;
|
|
127
|
+
/**
|
|
128
|
+
* Splits `money` into `parts` equal shares without losing or gaining a single minor unit.
|
|
129
|
+
* Equivalent to `allocate(money, Array.from({ length: parts }, () => 1))`.
|
|
130
|
+
*
|
|
131
|
+
* @throws {CoinsError} If `parts` is not a positive integer (≥ 1).
|
|
132
|
+
*
|
|
133
|
+
* @example
|
|
134
|
+
* ```ts
|
|
135
|
+
* splitEvenly(money('10.00', 'USD'), 3)
|
|
136
|
+
* // → [$3.34, $3.33, $3.33]
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
export declare function splitEvenly(m: Money, parts: number): [Money, ...Money[]];
|
|
140
|
+
/**
|
|
141
|
+
* Clamps `m` to the inclusive range `[lower, upper]`.
|
|
142
|
+
*
|
|
143
|
+
* @throws {CurrencyMismatchError} If `m`, `lower`, or `upper` have different currencies.
|
|
144
|
+
* @throws {CoinsError} If `lower > upper`.
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* ```ts
|
|
148
|
+
* clamp(money('5.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $5.00
|
|
149
|
+
* clamp(money('0.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $1.00
|
|
150
|
+
* clamp(money('15.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $10.00
|
|
151
|
+
* ```
|
|
152
|
+
*/
|
|
153
|
+
export declare function clamp(m: Money, lower: Money, upper: Money): Money;
|
|
154
|
+
/** Returns the absolute value of `money`. Negative amounts become positive. */
|
|
155
|
+
export declare function abs(m: Money): Money;
|
|
156
|
+
/** Returns `money` with its sign flipped. */
|
|
157
|
+
export declare function negate(m: Money): Money;
|
|
158
|
+
/**
|
|
159
|
+
* Compares two `Money` values. Returns `-1`, `0`, or `1`.
|
|
160
|
+
* Throws if their currencies differ.
|
|
161
|
+
*/
|
|
162
|
+
export declare function compare(a: Money, b: Money): -1 | 0 | 1;
|
|
163
|
+
/**
|
|
164
|
+
* Returns `true` if both `Money` values have the same currency and amount.
|
|
165
|
+
* Returns `false` if currencies differ — safe to use in `.filter()` and conditional chains.
|
|
166
|
+
*/
|
|
167
|
+
export declare function isEqual(a: Money, b: Money): boolean;
|
|
168
|
+
/** Returns `true` if `a` is strictly greater than `b`. Throws on currency mismatch. */
|
|
169
|
+
export declare function greaterThan(a: Money, b: Money): boolean;
|
|
170
|
+
/** Returns `true` if `a` is greater than or equal to `b`. Throws on currency mismatch. */
|
|
171
|
+
export declare function greaterThanOrEqual(a: Money, b: Money): boolean;
|
|
172
|
+
/** Returns `true` if `a` is strictly less than `b`. Throws on currency mismatch. */
|
|
173
|
+
export declare function lessThan(a: Money, b: Money): boolean;
|
|
174
|
+
/** Returns `true` if `a` is less than or equal to `b`. Throws on currency mismatch. */
|
|
175
|
+
export declare function lessThanOrEqual(a: Money, b: Money): boolean;
|
|
176
|
+
/** Returns `true` if the amount is exactly zero. */
|
|
177
|
+
export declare function isZero(m: Money): boolean;
|
|
178
|
+
/** Returns `true` if the amount is strictly positive (> 0). */
|
|
179
|
+
export declare function isPositive(m: Money): boolean;
|
|
180
|
+
/** Returns `true` if the amount is strictly negative (< 0). */
|
|
181
|
+
export declare function isNegative(m: Money): boolean;
|
|
182
|
+
/** Returns `true` if the amount is zero or positive (>= 0). */
|
|
183
|
+
export declare function isNonNegative(m: Money): boolean;
|
|
184
|
+
/** Returns `true` if the amount is zero or negative (<= 0). */
|
|
185
|
+
export declare function isNonPositive(m: Money): boolean;
|
|
186
|
+
/**
|
|
187
|
+
* Serializes a `Money` value to a plain-object JSON-safe form.
|
|
188
|
+
* `amount` is a bigint string (e.g. `'123456'`) to avoid `JSON.stringify` throwing.
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```ts
|
|
192
|
+
* toJSON(money('1234.56', 'USD')) // { amount: '123456', currency: 'USD' }
|
|
193
|
+
* JSON.stringify(toJSON(price)) // '{"amount":"123456","currency":"USD"}'
|
|
194
|
+
* ```
|
|
195
|
+
*/
|
|
196
|
+
export declare function toJSON(m: Money): MoneyJSON;
|
|
197
|
+
/**
|
|
198
|
+
* Deserializes a `MoneyJSON` object back into a `Money` value.
|
|
199
|
+
* Validates the currency code and the amount string.
|
|
200
|
+
*
|
|
201
|
+
* @example
|
|
202
|
+
* ```ts
|
|
203
|
+
* fromJSON({ amount: '123456', currency: 'USD' }) // { amount: 123456n, currency: 'USD' }
|
|
204
|
+
* ```
|
|
205
|
+
*/
|
|
206
|
+
export declare function fromJSON(json: MoneyJSON): Money;
|
|
207
|
+
/**
|
|
208
|
+
* Serializes a `Money` value to a decimal string (e.g. `'1234.56'`).
|
|
209
|
+
* Round-trips losslessly with `money()`.
|
|
210
|
+
*
|
|
211
|
+
* @example
|
|
212
|
+
* ```ts
|
|
213
|
+
* toDecimal(money('1234.56', 'USD')) // '1234.56'
|
|
214
|
+
* toDecimal(money(5n, 'USD')) // '0.05'
|
|
215
|
+
* toDecimal(money(1234n, 'JPY')) // '1234'
|
|
216
|
+
* ```
|
|
217
|
+
*/
|
|
218
|
+
export declare function toDecimal(m: Money): string;
|
|
219
|
+
/**
|
|
220
|
+
* Converts a `Money` value to a floating-point number.
|
|
221
|
+
* Useful for charting and display; **not** for arithmetic (lossy).
|
|
222
|
+
*
|
|
223
|
+
* @example
|
|
224
|
+
* ```ts
|
|
225
|
+
* toNumber(money('1234.56', 'USD')) // 1234.56
|
|
226
|
+
* ```
|
|
227
|
+
*/
|
|
228
|
+
export declare function toNumber(m: Money): number;
|
|
229
|
+
/**
|
|
230
|
+
* Rounds a `Money` value to fewer decimal places than the currency's default.
|
|
231
|
+
* `places` must be a non-negative integer in the range `0..currencyDecimals`.
|
|
232
|
+
*
|
|
233
|
+
* Useful for display purposes (e.g. rounding USD to whole dollars).
|
|
234
|
+
* @throws {CoinsError} If `places` is out of the allowed range.
|
|
235
|
+
*
|
|
236
|
+
* @param mode Rounding mode. Defaults to `'half-away-from-zero'`.
|
|
237
|
+
*
|
|
238
|
+
* @example
|
|
239
|
+
* ```ts
|
|
240
|
+
* roundTo(money('1234.56', 'USD'), 0) // $1235 (whole dollars)
|
|
241
|
+
* roundTo(money('1234.56', 'USD'), 1) // $1234.6
|
|
242
|
+
* roundTo(money('1234.56', 'USD'), 1, 'floor') // $1234.5
|
|
243
|
+
* roundTo(money('1234', 'JPY'), 0) // ¥1234 (no-op: JPY is already 0-decimal)
|
|
244
|
+
* ```
|
|
245
|
+
*/
|
|
246
|
+
export declare function roundTo(m: Money, places: number, mode?: RoundingMode): Money;
|
|
247
|
+
//# sourceMappingURL=money.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"money.d.ts","sourceRoot":"","sources":["../src/money.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAc5E,OAAO,EAAE,UAAU,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAInF;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,YAAY,GAAG,KAAK,CA8BrF;AAyBD;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,GAAG,KAAK,CAE1D;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,KAAK,CAWtD;AAID,kEAAkE;AAClE,wBAAgB,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,GAAG,KAAK,CAI7C;AAED,iEAAiE;AACjE,wBAAgB,QAAQ,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,GAAG,KAAK,CAIlD;AA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