@automattic/number-formatters 1.2.4 → 1.2.6
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/CHANGELOG.md +10 -0
- package/dist/index.cjs +701 -0
- package/dist/index.d.cts +302 -0
- package/dist/index.d.ts +302 -0
- package/dist/index.js +670 -0
- package/package.json +9 -12
- package/src/constants.ts +7 -4
- package/dist/cjs/constants.cjs +0 -9
- package/dist/cjs/create-number-formatters.cjs +0 -113
- package/dist/cjs/get-cached-formatter.cjs +0 -36
- package/dist/cjs/index.cjs +0 -10
- package/dist/cjs/number-format-currency/currencies.cjs +0 -488
- package/dist/cjs/number-format-currency/index.cjs +0 -376
- package/dist/cjs/number-format.cjs +0 -59
- package/dist/cjs/types.cjs +0 -2
- package/dist/esm/constants.js +0 -5
- package/dist/esm/create-number-formatters.js +0 -111
- package/dist/esm/get-cached-formatter.js +0 -32
- package/dist/esm/index.js +0 -6
- package/dist/esm/number-format-currency/currencies.js +0 -485
- package/dist/esm/number-format-currency/index.js +0 -371
- package/dist/esm/number-format.js +0 -55
- package/dist/esm/types.js +0 -1
- package/dist/types/constants.d.ts +0 -3
- package/dist/types/create-number-formatters.d.ts +0 -154
- package/dist/types/get-cached-formatter.d.ts +0 -17
- package/dist/types/index.d.ts +0 -4
- package/dist/types/number-format-currency/currencies.d.ts +0 -2
- package/dist/types/number-format-currency/index.d.ts +0 -91
- package/dist/types/number-format.d.ts +0 -22
- package/dist/types/types.d.ts +0 -142
package/dist/index.js
ADDED
|
@@ -0,0 +1,670 @@
|
|
|
1
|
+
import "@wordpress/date";
|
|
2
|
+
import debugFactory from "debug";
|
|
3
|
+
//#region src/get-cached-formatter.ts
|
|
4
|
+
const debug$1 = debugFactory("number-formatters:get-cached-formatter");
|
|
5
|
+
const formatterCache = /* @__PURE__ */ new Map();
|
|
6
|
+
/**
|
|
7
|
+
* Get a cached formatter for a given locale and options.
|
|
8
|
+
* @param params - The parameters for the formatter.
|
|
9
|
+
* @param params.locale - The locale to format the number in.
|
|
10
|
+
* @param params.options - Intl.NumberFormatOptions to pass to the formatter.
|
|
11
|
+
* @param params.fallbackLocale - The locale to fallback to if the locale is not supported.
|
|
12
|
+
* @param params.retries - The number of retries to attempt if the formatter is not created.
|
|
13
|
+
* @return {Intl.NumberFormat} A cached formatter for the given locale and options.
|
|
14
|
+
*/
|
|
15
|
+
function getCachedFormatter({ locale, fallbackLocale = "en", options, retries = 1 }) {
|
|
16
|
+
const cacheKey = JSON.stringify([locale, options]);
|
|
17
|
+
try {
|
|
18
|
+
return formatterCache.get(cacheKey) ?? formatterCache.set(cacheKey, new Intl.NumberFormat(locale, options)).get(cacheKey);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
debug$1(`Intl.NumberFormat was called with a non-existent locale "${locale}"; falling back to ${fallbackLocale}`);
|
|
21
|
+
if (retries) return getCachedFormatter({
|
|
22
|
+
locale: fallbackLocale,
|
|
23
|
+
options,
|
|
24
|
+
retries: retries - 1
|
|
25
|
+
});
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/number-format-currency/currencies.ts
|
|
31
|
+
const defaultCurrencyOverrides = {
|
|
32
|
+
AED: { symbol: "د.إ." },
|
|
33
|
+
AFN: { symbol: "؋" },
|
|
34
|
+
ALL: { symbol: "Lek" },
|
|
35
|
+
AMD: { symbol: "֏" },
|
|
36
|
+
ANG: { symbol: "ƒ" },
|
|
37
|
+
AOA: { symbol: "Kz" },
|
|
38
|
+
ARS: { symbol: "$" },
|
|
39
|
+
AUD: { symbol: "A$" },
|
|
40
|
+
AWG: { symbol: "ƒ" },
|
|
41
|
+
AZN: { symbol: "₼" },
|
|
42
|
+
BAM: { symbol: "КМ" },
|
|
43
|
+
BBD: { symbol: "Bds$" },
|
|
44
|
+
BDT: { symbol: "৳" },
|
|
45
|
+
BGN: { symbol: "лв." },
|
|
46
|
+
BHD: { symbol: "د.ب." },
|
|
47
|
+
BIF: { symbol: "FBu" },
|
|
48
|
+
BMD: { symbol: "$" },
|
|
49
|
+
BND: { symbol: "$" },
|
|
50
|
+
BOB: { symbol: "Bs" },
|
|
51
|
+
BRL: { symbol: "R$" },
|
|
52
|
+
BSD: { symbol: "$" },
|
|
53
|
+
BTC: { symbol: "Ƀ" },
|
|
54
|
+
BTN: { symbol: "Nu." },
|
|
55
|
+
BWP: { symbol: "P" },
|
|
56
|
+
BYR: { symbol: "р." },
|
|
57
|
+
BZD: { symbol: "BZ$" },
|
|
58
|
+
CAD: { symbol: "C$" },
|
|
59
|
+
CDF: { symbol: "FC" },
|
|
60
|
+
CHF: { symbol: "CHF" },
|
|
61
|
+
CLP: { symbol: "$" },
|
|
62
|
+
CNY: { symbol: "¥" },
|
|
63
|
+
COP: { symbol: "$" },
|
|
64
|
+
CRC: { symbol: "₡" },
|
|
65
|
+
CUC: { symbol: "CUC" },
|
|
66
|
+
CUP: { symbol: "$MN" },
|
|
67
|
+
CVE: { symbol: "$" },
|
|
68
|
+
CZK: { symbol: "Kč" },
|
|
69
|
+
DJF: { symbol: "Fdj" },
|
|
70
|
+
DKK: { symbol: "kr." },
|
|
71
|
+
DOP: { symbol: "RD$" },
|
|
72
|
+
DZD: { symbol: "د.ج." },
|
|
73
|
+
EGP: { symbol: "ج.م." },
|
|
74
|
+
ERN: { symbol: "Nfk" },
|
|
75
|
+
ETB: { symbol: "ETB" },
|
|
76
|
+
EUR: { symbol: "€" },
|
|
77
|
+
FJD: { symbol: "FJ$" },
|
|
78
|
+
FKP: { symbol: "£" },
|
|
79
|
+
GBP: { symbol: "£" },
|
|
80
|
+
GEL: { symbol: "Lari" },
|
|
81
|
+
GHS: { symbol: "₵" },
|
|
82
|
+
GIP: { symbol: "£" },
|
|
83
|
+
GMD: { symbol: "D" },
|
|
84
|
+
GNF: { symbol: "FG" },
|
|
85
|
+
GTQ: { symbol: "Q" },
|
|
86
|
+
GYD: { symbol: "G$" },
|
|
87
|
+
HKD: { symbol: "HK$" },
|
|
88
|
+
HNL: { symbol: "L." },
|
|
89
|
+
HRK: { symbol: "kn" },
|
|
90
|
+
HTG: { symbol: "G" },
|
|
91
|
+
HUF: { symbol: "Ft" },
|
|
92
|
+
IDR: { symbol: "Rp" },
|
|
93
|
+
ILS: { symbol: "₪" },
|
|
94
|
+
INR: { symbol: "₹" },
|
|
95
|
+
IQD: { symbol: "د.ع." },
|
|
96
|
+
IRR: { symbol: "﷼" },
|
|
97
|
+
ISK: { symbol: "kr." },
|
|
98
|
+
JMD: { symbol: "J$" },
|
|
99
|
+
JOD: { symbol: "د.ا." },
|
|
100
|
+
JPY: { symbol: "¥" },
|
|
101
|
+
KES: { symbol: "S" },
|
|
102
|
+
KGS: { symbol: "сом" },
|
|
103
|
+
KHR: { symbol: "៛" },
|
|
104
|
+
KMF: { symbol: "CF" },
|
|
105
|
+
KPW: { symbol: "₩" },
|
|
106
|
+
KRW: { symbol: "₩" },
|
|
107
|
+
KWD: { symbol: "د.ك." },
|
|
108
|
+
KYD: { symbol: "$" },
|
|
109
|
+
KZT: { symbol: "₸" },
|
|
110
|
+
LAK: { symbol: "₭" },
|
|
111
|
+
LBP: { symbol: "ل.ل." },
|
|
112
|
+
LKR: { symbol: "₨" },
|
|
113
|
+
LRD: { symbol: "L$" },
|
|
114
|
+
LSL: { symbol: "M" },
|
|
115
|
+
LYD: { symbol: "د.ل." },
|
|
116
|
+
MAD: { symbol: "د.م." },
|
|
117
|
+
MDL: { symbol: "lei" },
|
|
118
|
+
MGA: { symbol: "Ar" },
|
|
119
|
+
MKD: { symbol: "ден." },
|
|
120
|
+
MMK: { symbol: "K" },
|
|
121
|
+
MNT: { symbol: "₮" },
|
|
122
|
+
MOP: { symbol: "MOP$" },
|
|
123
|
+
MRO: { symbol: "UM" },
|
|
124
|
+
MTL: { symbol: "₤" },
|
|
125
|
+
MUR: { symbol: "₨" },
|
|
126
|
+
MVR: { symbol: "MVR" },
|
|
127
|
+
MWK: { symbol: "MK" },
|
|
128
|
+
MXN: { symbol: "MX$" },
|
|
129
|
+
MYR: { symbol: "RM" },
|
|
130
|
+
MZN: { symbol: "MT" },
|
|
131
|
+
NAD: { symbol: "N$" },
|
|
132
|
+
NGN: { symbol: "₦" },
|
|
133
|
+
NIO: { symbol: "C$" },
|
|
134
|
+
NOK: { symbol: "kr" },
|
|
135
|
+
NPR: { symbol: "₨" },
|
|
136
|
+
NZD: { symbol: "NZ$" },
|
|
137
|
+
OMR: { symbol: "﷼" },
|
|
138
|
+
PAB: { symbol: "B/." },
|
|
139
|
+
PEN: { symbol: "S/." },
|
|
140
|
+
PGK: { symbol: "K" },
|
|
141
|
+
PHP: { symbol: "₱" },
|
|
142
|
+
PKR: { symbol: "₨" },
|
|
143
|
+
PLN: { symbol: "zł" },
|
|
144
|
+
PYG: { symbol: "₲" },
|
|
145
|
+
QAR: { symbol: "﷼" },
|
|
146
|
+
RON: { symbol: "lei" },
|
|
147
|
+
RSD: { symbol: "Дин." },
|
|
148
|
+
RUB: { symbol: "₽" },
|
|
149
|
+
RWF: { symbol: "RWF" },
|
|
150
|
+
SAR: { symbol: "﷼" },
|
|
151
|
+
SBD: { symbol: "S$" },
|
|
152
|
+
SCR: { symbol: "₨" },
|
|
153
|
+
SDD: { symbol: "LSd" },
|
|
154
|
+
SDG: { symbol: "£" },
|
|
155
|
+
SEK: { symbol: "kr" },
|
|
156
|
+
SGD: { symbol: "S$" },
|
|
157
|
+
SHP: { symbol: "£" },
|
|
158
|
+
SLL: { symbol: "Le" },
|
|
159
|
+
SOS: { symbol: "S" },
|
|
160
|
+
SRD: { symbol: "$" },
|
|
161
|
+
STD: { symbol: "Db" },
|
|
162
|
+
SVC: { symbol: "₡" },
|
|
163
|
+
SYP: { symbol: "£" },
|
|
164
|
+
SZL: { symbol: "E" },
|
|
165
|
+
THB: { symbol: "฿" },
|
|
166
|
+
TJS: { symbol: "TJS" },
|
|
167
|
+
TMT: { symbol: "m" },
|
|
168
|
+
TND: { symbol: "د.ت." },
|
|
169
|
+
TOP: { symbol: "T$" },
|
|
170
|
+
TRY: { symbol: "TL" },
|
|
171
|
+
TTD: { symbol: "TT$" },
|
|
172
|
+
TVD: { symbol: "$T" },
|
|
173
|
+
TWD: { symbol: "NT$" },
|
|
174
|
+
TZS: { symbol: "TSh" },
|
|
175
|
+
UAH: { symbol: "₴" },
|
|
176
|
+
UGX: { symbol: "USh" },
|
|
177
|
+
USD: {},
|
|
178
|
+
UYU: { symbol: "$U" },
|
|
179
|
+
UZS: { symbol: "сўм" },
|
|
180
|
+
VEB: { symbol: "Bs." },
|
|
181
|
+
VEF: { symbol: "Bs. F." },
|
|
182
|
+
VND: { symbol: "₫" },
|
|
183
|
+
VUV: { symbol: "VT" },
|
|
184
|
+
WST: { symbol: "WS$" },
|
|
185
|
+
XAF: { symbol: "F" },
|
|
186
|
+
XCD: { symbol: "$" },
|
|
187
|
+
XOF: { symbol: "F" },
|
|
188
|
+
XPF: { symbol: "F" },
|
|
189
|
+
YER: { symbol: "﷼" },
|
|
190
|
+
ZAR: { symbol: "R" },
|
|
191
|
+
ZMW: { symbol: "ZK" },
|
|
192
|
+
WON: { symbol: "₩" }
|
|
193
|
+
};
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region src/number-format-currency/index.ts
|
|
196
|
+
const debug = debugFactory("number-formatters:number-format-currency");
|
|
197
|
+
/**
|
|
198
|
+
* Retrieves the currency override for a given currency.
|
|
199
|
+
*
|
|
200
|
+
* If the currency is USD and the user is not in the US, it will return `US$`.
|
|
201
|
+
*
|
|
202
|
+
* Per-field merge order is: dynamic overrides (from `currencyOverrides`) → hard-coded defaults.
|
|
203
|
+
* This means a caller can supply a partial map (eg: only `decimal`) without losing the
|
|
204
|
+
* default `symbol`.
|
|
205
|
+
* @param currency - The currency to get the override for.
|
|
206
|
+
* @param geoLocation - The geo location of the user.
|
|
207
|
+
* @param currencyOverrides - Dynamic per-currency overrides supplied by the host application.
|
|
208
|
+
* @return {CurrencyOverride | undefined} The currency override.
|
|
209
|
+
*/
|
|
210
|
+
function getCurrencyOverride(currency, geoLocation, currencyOverrides) {
|
|
211
|
+
if (currency === "USD" && geoLocation && geoLocation !== "" && geoLocation !== "US") return {
|
|
212
|
+
symbol: "US$",
|
|
213
|
+
...currencyOverrides?.USD
|
|
214
|
+
};
|
|
215
|
+
const defaultOverride = defaultCurrencyOverrides[currency];
|
|
216
|
+
const dynamicOverride = currencyOverrides?.[currency];
|
|
217
|
+
if (!defaultOverride && !dynamicOverride) return;
|
|
218
|
+
return {
|
|
219
|
+
...defaultOverride,
|
|
220
|
+
...dynamicOverride
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Returns a valid currency code based on a shortlist of currency codes.
|
|
225
|
+
* Only currencies from the shortlist are allowed. Everything else will fall back to `FALLBACK_CURRENCY`.
|
|
226
|
+
* @param currency - The currency to get the valid currency for.
|
|
227
|
+
* @param geoLocation - The geo location of the user.
|
|
228
|
+
* @param currencyOverrides - Dynamic per-currency overrides supplied by the host application.
|
|
229
|
+
* @return {string} The valid currency.
|
|
230
|
+
*/
|
|
231
|
+
function getValidCurrency(currency, geoLocation, currencyOverrides) {
|
|
232
|
+
if (!getCurrencyOverride(currency, geoLocation, currencyOverrides)) {
|
|
233
|
+
debug(`getValidCurrency was called with a non-existent currency "${currency}"; falling back to USD`);
|
|
234
|
+
return "USD";
|
|
235
|
+
}
|
|
236
|
+
return currency;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Returns a currency formatter for a given currency.
|
|
240
|
+
* @param params - The parameters for the currency formatter.
|
|
241
|
+
* @param params.number - The number to format.
|
|
242
|
+
* @param params.currency - The currency to format.
|
|
243
|
+
* @param params.browserSafeLocale - The browser safe locale.
|
|
244
|
+
* @param params.forceLatin - Whether to force the latin locale.
|
|
245
|
+
* @param params.stripZeros - Whether to strip zeros.
|
|
246
|
+
* @param params.signForPositive - Whether to show the sign for positive numbers.
|
|
247
|
+
* @return {Intl.NumberFormat} The currency formatter.
|
|
248
|
+
*/
|
|
249
|
+
function getCurrencyFormatter({ number, currency, browserSafeLocale, forceLatin = true, stripZeros, signForPositive }) {
|
|
250
|
+
return getCachedFormatter({
|
|
251
|
+
locale: `${browserSafeLocale}${forceLatin ? "-u-nu-latn" : ""}`,
|
|
252
|
+
options: {
|
|
253
|
+
style: "currency",
|
|
254
|
+
currency,
|
|
255
|
+
...stripZeros && Number.isInteger(number) && {
|
|
256
|
+
/**
|
|
257
|
+
* There's an option called `trailingZeroDisplay` but it does not yet work
|
|
258
|
+
* in FF so we have to strip zeros manually.
|
|
259
|
+
*/
|
|
260
|
+
maximumFractionDigits: 0,
|
|
261
|
+
minimumFractionDigits: 0
|
|
262
|
+
},
|
|
263
|
+
...signForPositive && { signDisplay: "exceptZero" }
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Hard-coded smallest-unit exponent overrides for currencies where browser ICU's
|
|
269
|
+
* `maximumFractionDigits` disagrees with the API's smallest-unit encoding.
|
|
270
|
+
*
|
|
271
|
+
* This list exists as a safety net for callers that have not yet wired up the
|
|
272
|
+
* dynamic `currencyOverrides` path (eg: the WPCOM currencies endpoint). Once a
|
|
273
|
+
* host application provides overrides via `setCurrencyOverrides`, those take
|
|
274
|
+
* precedence on a per-currency basis.
|
|
275
|
+
*
|
|
276
|
+
* Keep this list minimal — the backend is the source of truth for the API's
|
|
277
|
+
* smallest-unit encoding, so adding speculative entries here risks silent
|
|
278
|
+
* drift. Only add a currency once we've verified that browsers report a
|
|
279
|
+
* value the API does not use.
|
|
280
|
+
*
|
|
281
|
+
* - IDR: modern Chrome / Node 24+ ICU reports 0; the API encodes with exponent 2.
|
|
282
|
+
* - HUF: same browser/API divergence as IDR.
|
|
283
|
+
*/
|
|
284
|
+
const SMALLEST_UNIT_EXPONENT_OVERRIDES = {
|
|
285
|
+
IDR: 2,
|
|
286
|
+
HUF: 2
|
|
287
|
+
};
|
|
288
|
+
/**
|
|
289
|
+
* Returns the smallest unit exponent for a currency.
|
|
290
|
+
*
|
|
291
|
+
* Lookup order:
|
|
292
|
+
* 1. The dynamic `currencyOverrides[currency].decimal` if a host application has supplied one (typically via `setCurrencyOverrides`).
|
|
293
|
+
* 2. The hard-coded `SMALLEST_UNIT_EXPONENT_OVERRIDES` map.
|
|
294
|
+
* 3. The browser-derived display precision (`fallback`).
|
|
295
|
+
* @param currency - The currency code (ISO 4217)
|
|
296
|
+
* @param fallback - The browser-derived precision to use when no override applies
|
|
297
|
+
* @param currencyOverrides - Dynamic per-currency overrides supplied by the host application
|
|
298
|
+
* @return number - The smallest unit exponent
|
|
299
|
+
*/
|
|
300
|
+
function getSmallestUnitExponent(currency, fallback, currencyOverrides) {
|
|
301
|
+
const dynamicDecimal = currencyOverrides?.[currency]?.decimal;
|
|
302
|
+
if (typeof dynamicDecimal === "number") return dynamicDecimal;
|
|
303
|
+
return SMALLEST_UNIT_EXPONENT_OVERRIDES[currency] ?? fallback;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Returns the precision for a given locale and currency.
|
|
307
|
+
* @param browserSafeLocale - The browser safe locale.
|
|
308
|
+
* @param currency - The currency to get the precision for.
|
|
309
|
+
* @param forceLatin - Whether to force the latin locale.
|
|
310
|
+
* @return {number | undefined} The precision.
|
|
311
|
+
*/
|
|
312
|
+
function getPrecisionForLocaleAndCurrency(browserSafeLocale, currency, forceLatin) {
|
|
313
|
+
/**
|
|
314
|
+
* For regular numbers, the default is 3 if neither `minimumFractionDigits` or `maximumFractionDigits` are set,
|
|
315
|
+
* otherwise the greatest betweem `minimumFractionDigits` and 3.
|
|
316
|
+
*
|
|
317
|
+
* For currencies, the default is dependent on the currency.
|
|
318
|
+
*
|
|
319
|
+
* This may also result in undefined, for several reasons:
|
|
320
|
+
* see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#significantdigitsfractiondigits_default_values
|
|
321
|
+
*/
|
|
322
|
+
return getCurrencyFormatter({
|
|
323
|
+
number: 0,
|
|
324
|
+
currency,
|
|
325
|
+
browserSafeLocale,
|
|
326
|
+
forceLatin
|
|
327
|
+
}).resolvedOptions().maximumFractionDigits;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Scales a number to a specified precision and rounds it to that precision.
|
|
331
|
+
* It ensures that all currency values are consistently rounded to the desired precision,
|
|
332
|
+
* avoiding issues with floating-point arithmetic.
|
|
333
|
+
* @param number - The number to scale.
|
|
334
|
+
* @param currencyPrecision - The precision to scale the number to.
|
|
335
|
+
* @return {number} The scaled number.
|
|
336
|
+
*/
|
|
337
|
+
function scaleNumberForPrecision(number, currencyPrecision) {
|
|
338
|
+
const scale = Math.pow(10, currencyPrecision);
|
|
339
|
+
return Math.round(number * scale) / scale;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Prepares a number for formatting.
|
|
343
|
+
* @param number - The number to prepare.
|
|
344
|
+
* @param currencyPrecision - The display precision (from the browser) to round the result to.
|
|
345
|
+
* @param currency - The currency code, used to look up any smallest-unit exponent override.
|
|
346
|
+
* @param isSmallestUnit - Whether the number is the smallest unit of a currency.
|
|
347
|
+
* @param currencyOverrides - Dynamic per-currency overrides supplied by the host application.
|
|
348
|
+
* @return {number} The prepared number.
|
|
349
|
+
*/
|
|
350
|
+
function prepareNumberForFormatting(number, currencyPrecision, currency, isSmallestUnit, currencyOverrides) {
|
|
351
|
+
if (isNaN(number)) {
|
|
352
|
+
debug("formatCurrency was called with NaN");
|
|
353
|
+
return 0;
|
|
354
|
+
}
|
|
355
|
+
if (isSmallestUnit) {
|
|
356
|
+
if (!Number.isInteger(number)) debug("formatCurrency was called with isSmallestUnit and a float which will be rounded", number);
|
|
357
|
+
const smallestUnitDivisor = 10 ** getSmallestUnitExponent(currency, currencyPrecision, currencyOverrides);
|
|
358
|
+
return scaleNumberForPrecision(Math.round(number) / smallestUnitDivisor, currencyPrecision);
|
|
359
|
+
}
|
|
360
|
+
return scaleNumberForPrecision(number, currencyPrecision);
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Formats money with a given currency code.
|
|
364
|
+
*
|
|
365
|
+
* The currency will define the properties to use for this formatting, but
|
|
366
|
+
* those properties can be overridden using the options. Be careful when doing
|
|
367
|
+
* this.
|
|
368
|
+
*
|
|
369
|
+
* For currencies that include decimals, this will always return the amount
|
|
370
|
+
* with decimals included, even if those decimals are zeros. To exclude the
|
|
371
|
+
* zeros, use the `stripZeros` option. For example, the function will normally
|
|
372
|
+
* format `10.00` in `USD` as `$10.00` but when this option is true, it will
|
|
373
|
+
* return `$10` instead.
|
|
374
|
+
*
|
|
375
|
+
* Since rounding errors are common in floating point math, sometimes a price
|
|
376
|
+
* is provided as an integer in the smallest unit of a currency (eg: cents in
|
|
377
|
+
* USD or yen in JPY). Set the `isSmallestUnit` to change the function to
|
|
378
|
+
* operate on integer numbers instead. If this option is not set or false, the
|
|
379
|
+
* function will format the amount `1025` in `USD` as `$1,025.00`, but when the
|
|
380
|
+
* option is true, it will return `$10.25` instead.
|
|
381
|
+
*
|
|
382
|
+
* If the number is NaN, it will be treated as 0.
|
|
383
|
+
*
|
|
384
|
+
* If the currency code is not known, this will assume a default currency
|
|
385
|
+
* similar to USD.
|
|
386
|
+
*
|
|
387
|
+
* If `isSmallestUnit` is set and the number is not an integer, it will be
|
|
388
|
+
* rounded to an integer.
|
|
389
|
+
*
|
|
390
|
+
* @param params - The parameters for the currency formatter.
|
|
391
|
+
* @param params.number - The number to format.
|
|
392
|
+
* @param params.browserSafeLocale - The browser safe locale.
|
|
393
|
+
* @param params.currency - The currency to format.
|
|
394
|
+
* @param params.stripZeros - Whether to strip zeros.
|
|
395
|
+
* @param params.isSmallestUnit - Whether the number is the smallest unit of a currency.
|
|
396
|
+
* @param params.signForPositive - Whether to show the sign for positive numbers.
|
|
397
|
+
* @param params.geoLocation - The geo location of the user.
|
|
398
|
+
* @param params.forceLatin - Whether to force the latin locale.
|
|
399
|
+
* @param params.currencyOverrides - Dynamic per-currency overrides supplied by the host application.
|
|
400
|
+
* @return {string} A formatted string.
|
|
401
|
+
*/
|
|
402
|
+
const numberFormatCurrency = ({ number, browserSafeLocale, currency, stripZeros, isSmallestUnit, signForPositive, geoLocation, forceLatin, currencyOverrides }) => {
|
|
403
|
+
const validCurrency = getValidCurrency(currency, geoLocation, currencyOverrides);
|
|
404
|
+
const currencyOverride = getCurrencyOverride(validCurrency, geoLocation, currencyOverrides);
|
|
405
|
+
const currencyPrecision = getPrecisionForLocaleAndCurrency(browserSafeLocale, validCurrency, forceLatin);
|
|
406
|
+
if (isSmallestUnit && typeof currencyPrecision === "undefined") throw new Error(`Could not determine currency precision for ${validCurrency} in ${browserSafeLocale}`);
|
|
407
|
+
const numberAsFloat = prepareNumberForFormatting(number, currencyPrecision ?? 0, validCurrency, isSmallestUnit, currencyOverrides);
|
|
408
|
+
return getCurrencyFormatter({
|
|
409
|
+
number: numberAsFloat,
|
|
410
|
+
currency: validCurrency,
|
|
411
|
+
browserSafeLocale,
|
|
412
|
+
forceLatin,
|
|
413
|
+
stripZeros,
|
|
414
|
+
signForPositive
|
|
415
|
+
}).formatToParts(numberAsFloat).reduce((formatted, part) => {
|
|
416
|
+
switch (part.type) {
|
|
417
|
+
case "currency":
|
|
418
|
+
if (currencyOverride?.symbol) return formatted + currencyOverride.symbol;
|
|
419
|
+
return formatted + part.value;
|
|
420
|
+
default: return formatted + part.value;
|
|
421
|
+
}
|
|
422
|
+
}, "");
|
|
423
|
+
};
|
|
424
|
+
/**
|
|
425
|
+
* Returns a formatted price object which can be used to manually render a
|
|
426
|
+
* formatted currency (eg: if you wanted to render the currency symbol in a
|
|
427
|
+
* different font size).
|
|
428
|
+
*
|
|
429
|
+
* The currency will define the properties to use for this formatting, but
|
|
430
|
+
* those properties can be overridden using the options. Be careful when doing
|
|
431
|
+
* this.
|
|
432
|
+
*
|
|
433
|
+
* For currencies that include decimals, this will always return the amount
|
|
434
|
+
* with decimals included, even if those decimals are zeros. To exclude the
|
|
435
|
+
* zeros, use the `stripZeros` option. For example, the function will normally
|
|
436
|
+
* format `10.00` in `USD` as `$10.00` but when this option is true, it will
|
|
437
|
+
* return `$10` instead.
|
|
438
|
+
*
|
|
439
|
+
* Since rounding errors are common in floating point math, sometimes a price
|
|
440
|
+
* is provided as an integer in the smallest unit of a currency (eg: cents in
|
|
441
|
+
* USD or yen in JPY). Set the `isSmallestUnit` to change the function to
|
|
442
|
+
* operate on integer numbers instead. If this option is not set or false, the
|
|
443
|
+
* function will format the amount `1025` in `USD` as `$1,025.00`, but when the
|
|
444
|
+
* option is true, it will return `$10.25` instead.
|
|
445
|
+
*
|
|
446
|
+
* Note that the `integer` return value of this function is not a number, but a
|
|
447
|
+
* locale-formatted string which may include symbols like spaces, commas, or
|
|
448
|
+
* periods as group separators. Similarly, the `fraction` property is a string
|
|
449
|
+
* that contains the decimal separator.
|
|
450
|
+
*
|
|
451
|
+
* If the number is NaN, it will be treated as 0.
|
|
452
|
+
*
|
|
453
|
+
* If the currency code is not known, this will assume a default currency
|
|
454
|
+
* similar to USD.
|
|
455
|
+
*
|
|
456
|
+
* If `isSmallestUnit` is set and the number is not an integer, it will be
|
|
457
|
+
* rounded to an integer.
|
|
458
|
+
*
|
|
459
|
+
* @param params - The parameters for the currency formatter.
|
|
460
|
+
* @param params.number - The number to format.
|
|
461
|
+
* @param params.browserSafeLocale - The browser safe locale.
|
|
462
|
+
* @param params.currency - The currency to format.
|
|
463
|
+
* @param params.stripZeros - Whether to strip zeros.
|
|
464
|
+
* @param params.isSmallestUnit - Whether the number is the smallest unit of a currency.
|
|
465
|
+
* @param params.signForPositive - Whether to show the sign for positive numbers.
|
|
466
|
+
* @param params.geoLocation - The geo location of the user.
|
|
467
|
+
* @param params.forceLatin - Whether to force the latin locale.
|
|
468
|
+
* @param params.currencyOverrides - Dynamic per-currency overrides supplied by the host application.
|
|
469
|
+
* @return {CurrencyObject} A formatted string e.g. { symbol:'$', integer: '$99', fraction: '.99', sign: '-' }
|
|
470
|
+
*/
|
|
471
|
+
const getCurrencyObject$1 = ({ number, browserSafeLocale, currency, stripZeros, isSmallestUnit, signForPositive, geoLocation, forceLatin, currencyOverrides }) => {
|
|
472
|
+
const validCurrency = getValidCurrency(currency, geoLocation, currencyOverrides);
|
|
473
|
+
const currencyOverride = getCurrencyOverride(validCurrency, geoLocation, currencyOverrides);
|
|
474
|
+
const numberAsFloat = prepareNumberForFormatting(number, getPrecisionForLocaleAndCurrency(browserSafeLocale, validCurrency, forceLatin) ?? 0, validCurrency, isSmallestUnit, currencyOverrides);
|
|
475
|
+
const parts = getCurrencyFormatter({
|
|
476
|
+
number: numberAsFloat,
|
|
477
|
+
currency: validCurrency,
|
|
478
|
+
browserSafeLocale,
|
|
479
|
+
forceLatin,
|
|
480
|
+
stripZeros,
|
|
481
|
+
signForPositive
|
|
482
|
+
}).formatToParts(numberAsFloat);
|
|
483
|
+
let sign = "";
|
|
484
|
+
let symbol = "$";
|
|
485
|
+
let symbolPosition = "before";
|
|
486
|
+
let hasAmountBeenSet = false;
|
|
487
|
+
let hasDecimalBeenSet = false;
|
|
488
|
+
let integer = "";
|
|
489
|
+
let fraction = "";
|
|
490
|
+
parts.forEach((part) => {
|
|
491
|
+
switch (part.type) {
|
|
492
|
+
case "currency":
|
|
493
|
+
symbol = currencyOverride?.symbol ?? part.value;
|
|
494
|
+
if (hasAmountBeenSet) symbolPosition = "after";
|
|
495
|
+
return;
|
|
496
|
+
case "group":
|
|
497
|
+
integer += part.value;
|
|
498
|
+
hasAmountBeenSet = true;
|
|
499
|
+
return;
|
|
500
|
+
case "decimal":
|
|
501
|
+
fraction += part.value;
|
|
502
|
+
hasAmountBeenSet = true;
|
|
503
|
+
hasDecimalBeenSet = true;
|
|
504
|
+
return;
|
|
505
|
+
case "integer":
|
|
506
|
+
integer += part.value;
|
|
507
|
+
hasAmountBeenSet = true;
|
|
508
|
+
return;
|
|
509
|
+
case "fraction":
|
|
510
|
+
fraction += part.value;
|
|
511
|
+
hasAmountBeenSet = true;
|
|
512
|
+
hasDecimalBeenSet = true;
|
|
513
|
+
return;
|
|
514
|
+
case "minusSign":
|
|
515
|
+
sign = "-";
|
|
516
|
+
return;
|
|
517
|
+
case "plusSign": sign = "+";
|
|
518
|
+
}
|
|
519
|
+
});
|
|
520
|
+
return {
|
|
521
|
+
sign,
|
|
522
|
+
symbol,
|
|
523
|
+
symbolPosition,
|
|
524
|
+
integer,
|
|
525
|
+
fraction,
|
|
526
|
+
hasNonZeroFraction: !Number.isInteger(numberAsFloat) && hasDecimalBeenSet,
|
|
527
|
+
floatValue: numberAsFloat
|
|
528
|
+
};
|
|
529
|
+
};
|
|
530
|
+
//#endregion
|
|
531
|
+
//#region src/number-format.ts
|
|
532
|
+
/**
|
|
533
|
+
* Formats numbers using locale settings and/or passed options.
|
|
534
|
+
* @param params - The parameters for the number formatter.
|
|
535
|
+
* @param params.browserSafeLocale - The browser safe locale.
|
|
536
|
+
* @param params.decimals - The number of decimal places to use.
|
|
537
|
+
* @param params.forceLatin - Whether to force the latin locale.
|
|
538
|
+
* @param params.numberFormatOptions - The options for the number formatter.
|
|
539
|
+
* @return {Intl.NumberFormat} The number formatter.
|
|
540
|
+
*/
|
|
541
|
+
const numberFormat = ({ browserSafeLocale, decimals = 0, forceLatin = true, numberFormatOptions = {} }) => {
|
|
542
|
+
return getCachedFormatter({
|
|
543
|
+
locale: `${browserSafeLocale}${forceLatin ? "-u-nu-latn" : ""}`,
|
|
544
|
+
options: {
|
|
545
|
+
minimumFractionDigits: decimals,
|
|
546
|
+
maximumFractionDigits: decimals,
|
|
547
|
+
...numberFormatOptions
|
|
548
|
+
}
|
|
549
|
+
});
|
|
550
|
+
};
|
|
551
|
+
/**
|
|
552
|
+
* Convenience method for formatting numbers in a compact notation e.g. 1K, 1M, etc.
|
|
553
|
+
* Basically sets `notation: 'compact'` and `maximumFractionDigits: 1` in the options.
|
|
554
|
+
* Everything is overridable by passing the `numberFormatOptions` option.
|
|
555
|
+
* If you want more digits, pass `maximumFractionDigits: 2`.
|
|
556
|
+
* @param params - The parameters for the number formatter.
|
|
557
|
+
* @param params.numberFormatOptions - The options for the number formatter.
|
|
558
|
+
* @return {Intl.NumberFormat} The number formatter.
|
|
559
|
+
*/
|
|
560
|
+
const numberFormatCompact = ({ numberFormatOptions = {}, ...params }) => numberFormat({
|
|
561
|
+
...params,
|
|
562
|
+
numberFormatOptions: {
|
|
563
|
+
notation: "compact",
|
|
564
|
+
maximumFractionDigits: 1,
|
|
565
|
+
...numberFormatOptions
|
|
566
|
+
}
|
|
567
|
+
});
|
|
568
|
+
//#endregion
|
|
569
|
+
//#region src/create-number-formatters.ts
|
|
570
|
+
/**
|
|
571
|
+
* Creates a NumberFormatters instance that provides number and currency formatting functionality with locale awareness
|
|
572
|
+
* @return {NumberFormatters} A NumberFormatters instance
|
|
573
|
+
*/
|
|
574
|
+
function createNumberFormatters() {
|
|
575
|
+
let localeState;
|
|
576
|
+
let geoLocationState;
|
|
577
|
+
let currencyOverridesState;
|
|
578
|
+
const setLocale = (locale) => {
|
|
579
|
+
/**
|
|
580
|
+
* The `Intl.NumberFormat` constructor fails only when there is a variant, divided by `_`.
|
|
581
|
+
* These suffixes should be removed. Values like `de-at` or `es-mx`
|
|
582
|
+
* should all be valid inputs for the constructor.
|
|
583
|
+
*/
|
|
584
|
+
localeState = locale;
|
|
585
|
+
};
|
|
586
|
+
const setCurrencyOverrides = (overrides) => {
|
|
587
|
+
currencyOverridesState = overrides;
|
|
588
|
+
};
|
|
589
|
+
/**
|
|
590
|
+
* Returns the locale defined on the module instance (through `setLocale`)
|
|
591
|
+
* or the "fallback locale" if no locale has been set.
|
|
592
|
+
*
|
|
593
|
+
* The "fallback locale" is defined as:
|
|
594
|
+
* - the current WP user locale, if available through `@wordpress/date` settings (assuming this runs in a WordPress context)
|
|
595
|
+
* - or the browser locale, if available through `window.navigator.language`
|
|
596
|
+
* - or the fallback locale constant (`FALLBACK_LOCALE`)
|
|
597
|
+
*
|
|
598
|
+
* @return {string} The locale to use for formatting.
|
|
599
|
+
*/
|
|
600
|
+
const getBrowserSafeLocale = () => {
|
|
601
|
+
const localeFromUserSettings = typeof window !== "undefined" ? window.wp?.date?.getSettings?.()?.l10n?.locale : void 0;
|
|
602
|
+
const localeFromNavigator = typeof window !== "undefined" ? window?.navigator?.language : void 0;
|
|
603
|
+
return (localeState ?? (localeFromUserSettings || localeFromNavigator) ?? "en").split("_")[0];
|
|
604
|
+
};
|
|
605
|
+
const setGeoLocation = (geoLocation) => {
|
|
606
|
+
geoLocationState = geoLocation;
|
|
607
|
+
};
|
|
608
|
+
const formatNumber = (number, { decimals = 0, forceLatin = true, numberFormatOptions = {} } = {}) => {
|
|
609
|
+
try {
|
|
610
|
+
return numberFormat({
|
|
611
|
+
browserSafeLocale: getBrowserSafeLocale(),
|
|
612
|
+
decimals,
|
|
613
|
+
forceLatin,
|
|
614
|
+
numberFormatOptions
|
|
615
|
+
}).format(number);
|
|
616
|
+
} catch {
|
|
617
|
+
return String(number);
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
const formatNumberCompact = (number, { decimals = 0, forceLatin = true, numberFormatOptions = {} } = {}) => {
|
|
621
|
+
try {
|
|
622
|
+
return numberFormatCompact({
|
|
623
|
+
browserSafeLocale: getBrowserSafeLocale(),
|
|
624
|
+
decimals,
|
|
625
|
+
forceLatin,
|
|
626
|
+
numberFormatOptions
|
|
627
|
+
}).format(number);
|
|
628
|
+
} catch {
|
|
629
|
+
return String(number);
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
const formatCurrency = (number, currency, { stripZeros = false, isSmallestUnit = false, signForPositive = false, forceLatin = true } = {}) => {
|
|
633
|
+
return numberFormatCurrency({
|
|
634
|
+
number,
|
|
635
|
+
currency,
|
|
636
|
+
browserSafeLocale: getBrowserSafeLocale(),
|
|
637
|
+
stripZeros,
|
|
638
|
+
isSmallestUnit,
|
|
639
|
+
signForPositive,
|
|
640
|
+
geoLocation: geoLocationState,
|
|
641
|
+
forceLatin,
|
|
642
|
+
currencyOverrides: currencyOverridesState
|
|
643
|
+
});
|
|
644
|
+
};
|
|
645
|
+
const getCurrencyObject = (number, currency, { stripZeros = false, isSmallestUnit = false, signForPositive = false, forceLatin = true } = {}) => {
|
|
646
|
+
return getCurrencyObject$1({
|
|
647
|
+
number,
|
|
648
|
+
currency,
|
|
649
|
+
browserSafeLocale: getBrowserSafeLocale(),
|
|
650
|
+
stripZeros,
|
|
651
|
+
isSmallestUnit,
|
|
652
|
+
signForPositive,
|
|
653
|
+
geoLocation: geoLocationState,
|
|
654
|
+
forceLatin,
|
|
655
|
+
currencyOverrides: currencyOverridesState
|
|
656
|
+
});
|
|
657
|
+
};
|
|
658
|
+
return {
|
|
659
|
+
setLocale,
|
|
660
|
+
setGeoLocation,
|
|
661
|
+
setCurrencyOverrides,
|
|
662
|
+
formatNumber,
|
|
663
|
+
formatNumberCompact,
|
|
664
|
+
formatCurrency,
|
|
665
|
+
getCurrencyObject
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
const { setLocale, setGeoLocation, setCurrencyOverrides, formatNumber, formatNumberCompact, formatCurrency, getCurrencyObject } = createNumberFormatters();
|
|
669
|
+
//#endregion
|
|
670
|
+
export { createNumberFormatters, formatCurrency, formatNumber, formatNumberCompact, getCurrencyObject, setCurrencyOverrides, setGeoLocation, setLocale };
|