@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
|
@@ -1,376 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getCurrencyObject = exports.numberFormatCurrency = void 0;
|
|
4
|
-
const tslib_1 = require("tslib");
|
|
5
|
-
const debug_1 = tslib_1.__importDefault(require("debug"));
|
|
6
|
-
const constants_ts_1 = require("../constants.cjs");
|
|
7
|
-
const get_cached_formatter_ts_1 = require("../get-cached-formatter.cjs");
|
|
8
|
-
const currencies_ts_1 = require("./currencies.cjs");
|
|
9
|
-
const debug = (0, debug_1.default)('number-formatters:number-format-currency');
|
|
10
|
-
/**
|
|
11
|
-
* Retrieves the currency override for a given currency.
|
|
12
|
-
*
|
|
13
|
-
* If the currency is USD and the user is not in the US, it will return `US$`.
|
|
14
|
-
*
|
|
15
|
-
* Per-field merge order is: dynamic overrides (from `currencyOverrides`) → hard-coded defaults.
|
|
16
|
-
* This means a caller can supply a partial map (eg: only `decimal`) without losing the
|
|
17
|
-
* default `symbol`.
|
|
18
|
-
* @param currency - The currency to get the override for.
|
|
19
|
-
* @param geoLocation - The geo location of the user.
|
|
20
|
-
* @param currencyOverrides - Dynamic per-currency overrides supplied by the host application.
|
|
21
|
-
* @return {CurrencyOverride | undefined} The currency override.
|
|
22
|
-
*/
|
|
23
|
-
function getCurrencyOverride(currency, geoLocation, currencyOverrides) {
|
|
24
|
-
if (currency === 'USD' && geoLocation && geoLocation !== '' && geoLocation !== 'US') {
|
|
25
|
-
return { symbol: 'US$', ...currencyOverrides?.USD };
|
|
26
|
-
}
|
|
27
|
-
const defaultOverride = currencies_ts_1.defaultCurrencyOverrides[currency];
|
|
28
|
-
const dynamicOverride = currencyOverrides?.[currency];
|
|
29
|
-
if (!defaultOverride && !dynamicOverride) {
|
|
30
|
-
return undefined;
|
|
31
|
-
}
|
|
32
|
-
return { ...defaultOverride, ...dynamicOverride };
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Returns a valid currency code based on a shortlist of currency codes.
|
|
36
|
-
* Only currencies from the shortlist are allowed. Everything else will fall back to `FALLBACK_CURRENCY`.
|
|
37
|
-
* @param currency - The currency to get the valid currency for.
|
|
38
|
-
* @param geoLocation - The geo location of the user.
|
|
39
|
-
* @param currencyOverrides - Dynamic per-currency overrides supplied by the host application.
|
|
40
|
-
* @return {string} The valid currency.
|
|
41
|
-
*/
|
|
42
|
-
function getValidCurrency(currency, geoLocation, currencyOverrides) {
|
|
43
|
-
if (!getCurrencyOverride(currency, geoLocation, currencyOverrides)) {
|
|
44
|
-
debug(`getValidCurrency was called with a non-existent currency "${currency}"; falling back to ${constants_ts_1.FALLBACK_CURRENCY}`);
|
|
45
|
-
return constants_ts_1.FALLBACK_CURRENCY;
|
|
46
|
-
}
|
|
47
|
-
return currency;
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Returns a currency formatter for a given currency.
|
|
51
|
-
* @param params - The parameters for the currency formatter.
|
|
52
|
-
* @param params.number - The number to format.
|
|
53
|
-
* @param params.currency - The currency to format.
|
|
54
|
-
* @param params.browserSafeLocale - The browser safe locale.
|
|
55
|
-
* @param params.forceLatin - Whether to force the latin locale.
|
|
56
|
-
* @param params.stripZeros - Whether to strip zeros.
|
|
57
|
-
* @param params.signForPositive - Whether to show the sign for positive numbers.
|
|
58
|
-
* @return {Intl.NumberFormat} The currency formatter.
|
|
59
|
-
*/
|
|
60
|
-
function getCurrencyFormatter({ number, currency, browserSafeLocale, forceLatin = true, stripZeros, signForPositive, }) {
|
|
61
|
-
/**
|
|
62
|
-
* `numberingSystem` is an option to `Intl.NumberFormat` and is available
|
|
63
|
-
* in all major browsers according to
|
|
64
|
-
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options
|
|
65
|
-
* but is not part of the TypeScript types in `es2020`:
|
|
66
|
-
*
|
|
67
|
-
* https://github.com/microsoft/TypeScript/blob/cfd472f7aa5a2010a3115263bf457b30c5b489f3/src/lib/es2020.intl.d.ts#L272
|
|
68
|
-
*
|
|
69
|
-
* However, it is part of the TypeScript types in `es5`:
|
|
70
|
-
*
|
|
71
|
-
* https://github.com/microsoft/TypeScript/blob/cfd472f7aa5a2010a3115263bf457b30c5b489f3/src/lib/es5.d.ts#L4310
|
|
72
|
-
*
|
|
73
|
-
* Apparently calypso uses `es2020` so we cannot use that option here right
|
|
74
|
-
* now. Instead, we will use the unicode extension to the locale, documented
|
|
75
|
-
* here:
|
|
76
|
-
*
|
|
77
|
-
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/numberingSystem#adding_a_numbering_system_via_the_locale_string
|
|
78
|
-
*/
|
|
79
|
-
const locale = `${browserSafeLocale}${forceLatin ? '-u-nu-latn' : ''}`;
|
|
80
|
-
const numberFormatOptions = {
|
|
81
|
-
style: 'currency',
|
|
82
|
-
currency,
|
|
83
|
-
...(stripZeros &&
|
|
84
|
-
Number.isInteger(number) && {
|
|
85
|
-
/**
|
|
86
|
-
* There's an option called `trailingZeroDisplay` but it does not yet work
|
|
87
|
-
* in FF so we have to strip zeros manually.
|
|
88
|
-
*/
|
|
89
|
-
maximumFractionDigits: 0,
|
|
90
|
-
minimumFractionDigits: 0,
|
|
91
|
-
}),
|
|
92
|
-
...(signForPositive && { signDisplay: 'exceptZero' }),
|
|
93
|
-
};
|
|
94
|
-
return (0, get_cached_formatter_ts_1.getCachedFormatter)({
|
|
95
|
-
locale,
|
|
96
|
-
options: numberFormatOptions,
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* Hard-coded smallest-unit exponent overrides for currencies where browser ICU's
|
|
101
|
-
* `maximumFractionDigits` disagrees with the API's smallest-unit encoding.
|
|
102
|
-
*
|
|
103
|
-
* This list exists as a safety net for callers that have not yet wired up the
|
|
104
|
-
* dynamic `currencyOverrides` path (eg: the WPCOM currencies endpoint). Once a
|
|
105
|
-
* host application provides overrides via `setCurrencyOverrides`, those take
|
|
106
|
-
* precedence on a per-currency basis.
|
|
107
|
-
*
|
|
108
|
-
* Keep this list minimal — the backend is the source of truth for the API's
|
|
109
|
-
* smallest-unit encoding, so adding speculative entries here risks silent
|
|
110
|
-
* drift. Only add a currency once we've verified that browsers report a
|
|
111
|
-
* value the API does not use.
|
|
112
|
-
*
|
|
113
|
-
* - IDR: modern Chrome / Node 24+ ICU reports 0; the API encodes with exponent 2.
|
|
114
|
-
* - HUF: same browser/API divergence as IDR.
|
|
115
|
-
*/
|
|
116
|
-
const SMALLEST_UNIT_EXPONENT_OVERRIDES = {
|
|
117
|
-
IDR: 2,
|
|
118
|
-
HUF: 2,
|
|
119
|
-
};
|
|
120
|
-
/**
|
|
121
|
-
* Returns the smallest unit exponent for a currency.
|
|
122
|
-
*
|
|
123
|
-
* Lookup order:
|
|
124
|
-
* 1. The dynamic `currencyOverrides[currency].decimal` if a host application has supplied one (typically via `setCurrencyOverrides`).
|
|
125
|
-
* 2. The hard-coded `SMALLEST_UNIT_EXPONENT_OVERRIDES` map.
|
|
126
|
-
* 3. The browser-derived display precision (`fallback`).
|
|
127
|
-
* @param currency - The currency code (ISO 4217)
|
|
128
|
-
* @param fallback - The browser-derived precision to use when no override applies
|
|
129
|
-
* @param currencyOverrides - Dynamic per-currency overrides supplied by the host application
|
|
130
|
-
* @return number - The smallest unit exponent
|
|
131
|
-
*/
|
|
132
|
-
function getSmallestUnitExponent(currency, fallback, currencyOverrides) {
|
|
133
|
-
const dynamicDecimal = currencyOverrides?.[currency]?.decimal;
|
|
134
|
-
if (typeof dynamicDecimal === 'number') {
|
|
135
|
-
return dynamicDecimal;
|
|
136
|
-
}
|
|
137
|
-
return SMALLEST_UNIT_EXPONENT_OVERRIDES[currency] ?? fallback;
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* Returns the precision for a given locale and currency.
|
|
141
|
-
* @param browserSafeLocale - The browser safe locale.
|
|
142
|
-
* @param currency - The currency to get the precision for.
|
|
143
|
-
* @param forceLatin - Whether to force the latin locale.
|
|
144
|
-
* @return {number | undefined} The precision.
|
|
145
|
-
*/
|
|
146
|
-
function getPrecisionForLocaleAndCurrency(browserSafeLocale, currency, forceLatin) {
|
|
147
|
-
const formatter = getCurrencyFormatter({ number: 0, currency, browserSafeLocale, forceLatin });
|
|
148
|
-
/**
|
|
149
|
-
* For regular numbers, the default is 3 if neither `minimumFractionDigits` or `maximumFractionDigits` are set,
|
|
150
|
-
* otherwise the greatest betweem `minimumFractionDigits` and 3.
|
|
151
|
-
*
|
|
152
|
-
* For currencies, the default is dependent on the currency.
|
|
153
|
-
*
|
|
154
|
-
* This may also result in undefined, for several reasons:
|
|
155
|
-
* see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#significantdigitsfractiondigits_default_values
|
|
156
|
-
*/
|
|
157
|
-
return formatter.resolvedOptions().maximumFractionDigits;
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Scales a number to a specified precision and rounds it to that precision.
|
|
161
|
-
* It ensures that all currency values are consistently rounded to the desired precision,
|
|
162
|
-
* avoiding issues with floating-point arithmetic.
|
|
163
|
-
* @param number - The number to scale.
|
|
164
|
-
* @param currencyPrecision - The precision to scale the number to.
|
|
165
|
-
* @return {number} The scaled number.
|
|
166
|
-
*/
|
|
167
|
-
function scaleNumberForPrecision(number, currencyPrecision) {
|
|
168
|
-
const scale = Math.pow(10, currencyPrecision);
|
|
169
|
-
return Math.round(number * scale) / scale;
|
|
170
|
-
}
|
|
171
|
-
/**
|
|
172
|
-
* Prepares a number for formatting.
|
|
173
|
-
* @param number - The number to prepare.
|
|
174
|
-
* @param currencyPrecision - The display precision (from the browser) to round the result to.
|
|
175
|
-
* @param currency - The currency code, used to look up any smallest-unit exponent override.
|
|
176
|
-
* @param isSmallestUnit - Whether the number is the smallest unit of a currency.
|
|
177
|
-
* @param currencyOverrides - Dynamic per-currency overrides supplied by the host application.
|
|
178
|
-
* @return {number} The prepared number.
|
|
179
|
-
*/
|
|
180
|
-
function prepareNumberForFormatting(number, currencyPrecision, currency, isSmallestUnit, currencyOverrides) {
|
|
181
|
-
if (isNaN(number)) {
|
|
182
|
-
debug('formatCurrency was called with NaN');
|
|
183
|
-
return 0;
|
|
184
|
-
}
|
|
185
|
-
if (isSmallestUnit) {
|
|
186
|
-
if (!Number.isInteger(number)) {
|
|
187
|
-
debug('formatCurrency was called with isSmallestUnit and a float which will be rounded', number);
|
|
188
|
-
}
|
|
189
|
-
const smallestUnitDivisor = 10 ** getSmallestUnitExponent(currency, currencyPrecision, currencyOverrides);
|
|
190
|
-
return scaleNumberForPrecision(Math.round(number) / smallestUnitDivisor, currencyPrecision);
|
|
191
|
-
}
|
|
192
|
-
return scaleNumberForPrecision(number, currencyPrecision);
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Formats money with a given currency code.
|
|
196
|
-
*
|
|
197
|
-
* The currency will define the properties to use for this formatting, but
|
|
198
|
-
* those properties can be overridden using the options. Be careful when doing
|
|
199
|
-
* this.
|
|
200
|
-
*
|
|
201
|
-
* For currencies that include decimals, this will always return the amount
|
|
202
|
-
* with decimals included, even if those decimals are zeros. To exclude the
|
|
203
|
-
* zeros, use the `stripZeros` option. For example, the function will normally
|
|
204
|
-
* format `10.00` in `USD` as `$10.00` but when this option is true, it will
|
|
205
|
-
* return `$10` instead.
|
|
206
|
-
*
|
|
207
|
-
* Since rounding errors are common in floating point math, sometimes a price
|
|
208
|
-
* is provided as an integer in the smallest unit of a currency (eg: cents in
|
|
209
|
-
* USD or yen in JPY). Set the `isSmallestUnit` to change the function to
|
|
210
|
-
* operate on integer numbers instead. If this option is not set or false, the
|
|
211
|
-
* function will format the amount `1025` in `USD` as `$1,025.00`, but when the
|
|
212
|
-
* option is true, it will return `$10.25` instead.
|
|
213
|
-
*
|
|
214
|
-
* If the number is NaN, it will be treated as 0.
|
|
215
|
-
*
|
|
216
|
-
* If the currency code is not known, this will assume a default currency
|
|
217
|
-
* similar to USD.
|
|
218
|
-
*
|
|
219
|
-
* If `isSmallestUnit` is set and the number is not an integer, it will be
|
|
220
|
-
* rounded to an integer.
|
|
221
|
-
*
|
|
222
|
-
* @param params - The parameters for the currency formatter.
|
|
223
|
-
* @param params.number - The number to format.
|
|
224
|
-
* @param params.browserSafeLocale - The browser safe locale.
|
|
225
|
-
* @param params.currency - The currency to format.
|
|
226
|
-
* @param params.stripZeros - Whether to strip zeros.
|
|
227
|
-
* @param params.isSmallestUnit - Whether the number is the smallest unit of a currency.
|
|
228
|
-
* @param params.signForPositive - Whether to show the sign for positive numbers.
|
|
229
|
-
* @param params.geoLocation - The geo location of the user.
|
|
230
|
-
* @param params.forceLatin - Whether to force the latin locale.
|
|
231
|
-
* @param params.currencyOverrides - Dynamic per-currency overrides supplied by the host application.
|
|
232
|
-
* @return {string} A formatted string.
|
|
233
|
-
*/
|
|
234
|
-
const numberFormatCurrency = ({ number, browserSafeLocale, currency, stripZeros, isSmallestUnit, signForPositive, geoLocation, forceLatin, currencyOverrides, }) => {
|
|
235
|
-
const validCurrency = getValidCurrency(currency, geoLocation, currencyOverrides);
|
|
236
|
-
const currencyOverride = getCurrencyOverride(validCurrency, geoLocation, currencyOverrides);
|
|
237
|
-
const currencyPrecision = getPrecisionForLocaleAndCurrency(browserSafeLocale, validCurrency, forceLatin);
|
|
238
|
-
if (isSmallestUnit && typeof currencyPrecision === 'undefined') {
|
|
239
|
-
throw new Error(`Could not determine currency precision for ${validCurrency} in ${browserSafeLocale}`);
|
|
240
|
-
}
|
|
241
|
-
const numberAsFloat = prepareNumberForFormatting(number, currencyPrecision ?? 0, validCurrency, isSmallestUnit, currencyOverrides);
|
|
242
|
-
const formatter = getCurrencyFormatter({
|
|
243
|
-
number: numberAsFloat,
|
|
244
|
-
currency: validCurrency,
|
|
245
|
-
browserSafeLocale,
|
|
246
|
-
forceLatin,
|
|
247
|
-
stripZeros,
|
|
248
|
-
signForPositive,
|
|
249
|
-
});
|
|
250
|
-
const parts = formatter.formatToParts(numberAsFloat);
|
|
251
|
-
return parts.reduce((formatted, part) => {
|
|
252
|
-
switch (part.type) {
|
|
253
|
-
case 'currency':
|
|
254
|
-
if (currencyOverride?.symbol) {
|
|
255
|
-
return formatted + currencyOverride.symbol;
|
|
256
|
-
}
|
|
257
|
-
return formatted + part.value;
|
|
258
|
-
default:
|
|
259
|
-
return formatted + part.value;
|
|
260
|
-
}
|
|
261
|
-
}, '');
|
|
262
|
-
};
|
|
263
|
-
exports.numberFormatCurrency = numberFormatCurrency;
|
|
264
|
-
/**
|
|
265
|
-
* Returns a formatted price object which can be used to manually render a
|
|
266
|
-
* formatted currency (eg: if you wanted to render the currency symbol in a
|
|
267
|
-
* different font size).
|
|
268
|
-
*
|
|
269
|
-
* The currency will define the properties to use for this formatting, but
|
|
270
|
-
* those properties can be overridden using the options. Be careful when doing
|
|
271
|
-
* this.
|
|
272
|
-
*
|
|
273
|
-
* For currencies that include decimals, this will always return the amount
|
|
274
|
-
* with decimals included, even if those decimals are zeros. To exclude the
|
|
275
|
-
* zeros, use the `stripZeros` option. For example, the function will normally
|
|
276
|
-
* format `10.00` in `USD` as `$10.00` but when this option is true, it will
|
|
277
|
-
* return `$10` instead.
|
|
278
|
-
*
|
|
279
|
-
* Since rounding errors are common in floating point math, sometimes a price
|
|
280
|
-
* is provided as an integer in the smallest unit of a currency (eg: cents in
|
|
281
|
-
* USD or yen in JPY). Set the `isSmallestUnit` to change the function to
|
|
282
|
-
* operate on integer numbers instead. If this option is not set or false, the
|
|
283
|
-
* function will format the amount `1025` in `USD` as `$1,025.00`, but when the
|
|
284
|
-
* option is true, it will return `$10.25` instead.
|
|
285
|
-
*
|
|
286
|
-
* Note that the `integer` return value of this function is not a number, but a
|
|
287
|
-
* locale-formatted string which may include symbols like spaces, commas, or
|
|
288
|
-
* periods as group separators. Similarly, the `fraction` property is a string
|
|
289
|
-
* that contains the decimal separator.
|
|
290
|
-
*
|
|
291
|
-
* If the number is NaN, it will be treated as 0.
|
|
292
|
-
*
|
|
293
|
-
* If the currency code is not known, this will assume a default currency
|
|
294
|
-
* similar to USD.
|
|
295
|
-
*
|
|
296
|
-
* If `isSmallestUnit` is set and the number is not an integer, it will be
|
|
297
|
-
* rounded to an integer.
|
|
298
|
-
*
|
|
299
|
-
* @param params - The parameters for the currency formatter.
|
|
300
|
-
* @param params.number - The number to format.
|
|
301
|
-
* @param params.browserSafeLocale - The browser safe locale.
|
|
302
|
-
* @param params.currency - The currency to format.
|
|
303
|
-
* @param params.stripZeros - Whether to strip zeros.
|
|
304
|
-
* @param params.isSmallestUnit - Whether the number is the smallest unit of a currency.
|
|
305
|
-
* @param params.signForPositive - Whether to show the sign for positive numbers.
|
|
306
|
-
* @param params.geoLocation - The geo location of the user.
|
|
307
|
-
* @param params.forceLatin - Whether to force the latin locale.
|
|
308
|
-
* @param params.currencyOverrides - Dynamic per-currency overrides supplied by the host application.
|
|
309
|
-
* @return {CurrencyObject} A formatted string e.g. { symbol:'$', integer: '$99', fraction: '.99', sign: '-' }
|
|
310
|
-
*/
|
|
311
|
-
const getCurrencyObject = ({ number, browserSafeLocale, currency, stripZeros, isSmallestUnit, signForPositive, geoLocation, forceLatin, currencyOverrides, }) => {
|
|
312
|
-
const validCurrency = getValidCurrency(currency, geoLocation, currencyOverrides);
|
|
313
|
-
const currencyOverride = getCurrencyOverride(validCurrency, geoLocation, currencyOverrides);
|
|
314
|
-
const currencyPrecision = getPrecisionForLocaleAndCurrency(browserSafeLocale, validCurrency, forceLatin);
|
|
315
|
-
const numberAsFloat = prepareNumberForFormatting(number, currencyPrecision ?? 0, validCurrency, isSmallestUnit, currencyOverrides);
|
|
316
|
-
const formatter = getCurrencyFormatter({
|
|
317
|
-
number: numberAsFloat,
|
|
318
|
-
currency: validCurrency,
|
|
319
|
-
browserSafeLocale,
|
|
320
|
-
forceLatin,
|
|
321
|
-
stripZeros,
|
|
322
|
-
signForPositive,
|
|
323
|
-
});
|
|
324
|
-
const parts = formatter.formatToParts(numberAsFloat);
|
|
325
|
-
let sign = '';
|
|
326
|
-
let symbol = '$';
|
|
327
|
-
let symbolPosition = 'before';
|
|
328
|
-
let hasAmountBeenSet = false;
|
|
329
|
-
let hasDecimalBeenSet = false;
|
|
330
|
-
let integer = '';
|
|
331
|
-
let fraction = '';
|
|
332
|
-
parts.forEach(part => {
|
|
333
|
-
switch (part.type) {
|
|
334
|
-
case 'currency':
|
|
335
|
-
symbol = currencyOverride?.symbol ?? part.value;
|
|
336
|
-
if (hasAmountBeenSet) {
|
|
337
|
-
symbolPosition = 'after';
|
|
338
|
-
}
|
|
339
|
-
return;
|
|
340
|
-
case 'group':
|
|
341
|
-
integer += part.value;
|
|
342
|
-
hasAmountBeenSet = true;
|
|
343
|
-
return;
|
|
344
|
-
case 'decimal':
|
|
345
|
-
fraction += part.value;
|
|
346
|
-
hasAmountBeenSet = true;
|
|
347
|
-
hasDecimalBeenSet = true;
|
|
348
|
-
return;
|
|
349
|
-
case 'integer':
|
|
350
|
-
integer += part.value;
|
|
351
|
-
hasAmountBeenSet = true;
|
|
352
|
-
return;
|
|
353
|
-
case 'fraction':
|
|
354
|
-
fraction += part.value;
|
|
355
|
-
hasAmountBeenSet = true;
|
|
356
|
-
hasDecimalBeenSet = true;
|
|
357
|
-
return;
|
|
358
|
-
case 'minusSign':
|
|
359
|
-
sign = '-';
|
|
360
|
-
return;
|
|
361
|
-
case 'plusSign':
|
|
362
|
-
sign = '+';
|
|
363
|
-
}
|
|
364
|
-
});
|
|
365
|
-
const hasNonZeroFraction = !Number.isInteger(numberAsFloat) && hasDecimalBeenSet;
|
|
366
|
-
return {
|
|
367
|
-
sign,
|
|
368
|
-
symbol,
|
|
369
|
-
symbolPosition,
|
|
370
|
-
integer,
|
|
371
|
-
fraction,
|
|
372
|
-
hasNonZeroFraction,
|
|
373
|
-
floatValue: numberAsFloat,
|
|
374
|
-
};
|
|
375
|
-
};
|
|
376
|
-
exports.getCurrencyObject = getCurrencyObject;
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.numberFormatCompact = exports.numberFormat = void 0;
|
|
4
|
-
const get_cached_formatter_ts_1 = require("./get-cached-formatter.cjs");
|
|
5
|
-
/**
|
|
6
|
-
* Formats numbers using locale settings and/or passed options.
|
|
7
|
-
* @param params - The parameters for the number formatter.
|
|
8
|
-
* @param params.browserSafeLocale - The browser safe locale.
|
|
9
|
-
* @param params.decimals - The number of decimal places to use.
|
|
10
|
-
* @param params.forceLatin - Whether to force the latin locale.
|
|
11
|
-
* @param params.numberFormatOptions - The options for the number formatter.
|
|
12
|
-
* @return {Intl.NumberFormat} The number formatter.
|
|
13
|
-
*/
|
|
14
|
-
const numberFormat = ({ browserSafeLocale, decimals = 0, forceLatin = true, numberFormatOptions = {}, }) => {
|
|
15
|
-
/**
|
|
16
|
-
* `numberingSystem` is an option to `Intl.NumberFormat` and is available
|
|
17
|
-
* in all major browsers according to
|
|
18
|
-
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options
|
|
19
|
-
* but is not part of the TypeScript types in `es2020`:
|
|
20
|
-
*
|
|
21
|
-
* https://github.com/microsoft/TypeScript/blob/cfd472f7aa5a2010a3115263bf457b30c5b489f3/src/lib/es2020.intl.d.ts#L272
|
|
22
|
-
*
|
|
23
|
-
* However, it is part of the TypeScript types in `es5`:
|
|
24
|
-
*
|
|
25
|
-
* https://github.com/microsoft/TypeScript/blob/cfd472f7aa5a2010a3115263bf457b30c5b489f3/src/lib/es5.d.ts#L4310
|
|
26
|
-
*
|
|
27
|
-
* Apparently calypso uses `es2020` so we cannot use that option here right
|
|
28
|
-
* now. Instead, we will use the unicode extension to the locale, documented
|
|
29
|
-
* here:
|
|
30
|
-
*
|
|
31
|
-
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/numberingSystem#adding_a_numbering_system_via_the_locale_string
|
|
32
|
-
*/
|
|
33
|
-
const locale = `${browserSafeLocale}${forceLatin ? '-u-nu-latn' : ''}`;
|
|
34
|
-
const options = {
|
|
35
|
-
minimumFractionDigits: decimals, // minimumFractionDigits default is 0
|
|
36
|
-
maximumFractionDigits: decimals, // maximumFractionDigits default is the greater between minimumFractionDigits and 3
|
|
37
|
-
...numberFormatOptions,
|
|
38
|
-
};
|
|
39
|
-
return (0, get_cached_formatter_ts_1.getCachedFormatter)({ locale, options });
|
|
40
|
-
};
|
|
41
|
-
exports.numberFormat = numberFormat;
|
|
42
|
-
/**
|
|
43
|
-
* Convenience method for formatting numbers in a compact notation e.g. 1K, 1M, etc.
|
|
44
|
-
* Basically sets `notation: 'compact'` and `maximumFractionDigits: 1` in the options.
|
|
45
|
-
* Everything is overridable by passing the `numberFormatOptions` option.
|
|
46
|
-
* If you want more digits, pass `maximumFractionDigits: 2`.
|
|
47
|
-
* @param params - The parameters for the number formatter.
|
|
48
|
-
* @param params.numberFormatOptions - The options for the number formatter.
|
|
49
|
-
* @return {Intl.NumberFormat} The number formatter.
|
|
50
|
-
*/
|
|
51
|
-
const numberFormatCompact = ({ numberFormatOptions = {}, ...params }) => numberFormat({
|
|
52
|
-
...params,
|
|
53
|
-
numberFormatOptions: {
|
|
54
|
-
notation: 'compact',
|
|
55
|
-
maximumFractionDigits: 1,
|
|
56
|
-
...numberFormatOptions,
|
|
57
|
-
},
|
|
58
|
-
});
|
|
59
|
-
exports.numberFormatCompact = numberFormatCompact;
|
package/dist/cjs/types.cjs
DELETED
package/dist/esm/constants.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
export const FALLBACK_LOCALE = 'en';
|
|
2
|
-
export const FALLBACK_CURRENCY = 'USD';
|
|
3
|
-
// This is just to hint to the dependency extraction tool that this package depends on @wordpress/date
|
|
4
|
-
// See: https://github.com/Automattic/jetpack/pull/47812#issuecomment-4142452829
|
|
5
|
-
export * from '@wordpress/date';
|
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
import { FALLBACK_LOCALE } from "./constants.js";
|
|
2
|
-
import { numberFormatCurrency, getCurrencyObject as getCurrencyObjectFromCurrencyFormatter, } from "./number-format-currency/index.js";
|
|
3
|
-
import { numberFormat, numberFormatCompact } from "./number-format.js";
|
|
4
|
-
/**
|
|
5
|
-
* Creates a NumberFormatters instance that provides number and currency formatting functionality with locale awareness
|
|
6
|
-
* @return {NumberFormatters} A NumberFormatters instance
|
|
7
|
-
*/
|
|
8
|
-
function createNumberFormatters() {
|
|
9
|
-
let localeState;
|
|
10
|
-
let geoLocationState;
|
|
11
|
-
let currencyOverridesState;
|
|
12
|
-
const setLocale = (locale) => {
|
|
13
|
-
/**
|
|
14
|
-
* The `Intl.NumberFormat` constructor fails only when there is a variant, divided by `_`.
|
|
15
|
-
* These suffixes should be removed. Values like `de-at` or `es-mx`
|
|
16
|
-
* should all be valid inputs for the constructor.
|
|
17
|
-
*/
|
|
18
|
-
localeState = locale;
|
|
19
|
-
};
|
|
20
|
-
const setCurrencyOverrides = (overrides) => {
|
|
21
|
-
currencyOverridesState = overrides;
|
|
22
|
-
};
|
|
23
|
-
/**
|
|
24
|
-
* Returns the locale defined on the module instance (through `setLocale`)
|
|
25
|
-
* or the "fallback locale" if no locale has been set.
|
|
26
|
-
*
|
|
27
|
-
* The "fallback locale" is defined as:
|
|
28
|
-
* - the current WP user locale, if available through `@wordpress/date` settings (assuming this runs in a WordPress context)
|
|
29
|
-
* - or the browser locale, if available through `window.navigator.language`
|
|
30
|
-
* - or the fallback locale constant (`FALLBACK_LOCALE`)
|
|
31
|
-
*
|
|
32
|
-
* @return {string} The locale to use for formatting.
|
|
33
|
-
*/
|
|
34
|
-
const getBrowserSafeLocale = () => {
|
|
35
|
-
// Accessing the user's locale from `@wordpress/date` package.
|
|
36
|
-
// This is a bit hacky but it's better than importing `@wordpress/date` and using its `getSettings` function,
|
|
37
|
-
// because it drags moment.js with it even though we don't need it here.
|
|
38
|
-
const localeFromUserSettings = typeof window !== 'undefined' ? window.wp?.date?.getSettings?.()?.l10n?.locale : undefined;
|
|
39
|
-
const localeFromNavigator = typeof window !== 'undefined' ? window?.navigator?.language : undefined;
|
|
40
|
-
return (localeState ??
|
|
41
|
-
(localeFromUserSettings || localeFromNavigator) ??
|
|
42
|
-
FALLBACK_LOCALE).split('_')[0];
|
|
43
|
-
};
|
|
44
|
-
const setGeoLocation = (geoLocation) => {
|
|
45
|
-
geoLocationState = geoLocation;
|
|
46
|
-
};
|
|
47
|
-
const formatNumber = (number, { decimals = 0, forceLatin = true, numberFormatOptions = {} } = {}) => {
|
|
48
|
-
try {
|
|
49
|
-
const formatter = numberFormat({
|
|
50
|
-
browserSafeLocale: getBrowserSafeLocale(),
|
|
51
|
-
decimals,
|
|
52
|
-
forceLatin,
|
|
53
|
-
numberFormatOptions,
|
|
54
|
-
});
|
|
55
|
-
return formatter.format(number);
|
|
56
|
-
}
|
|
57
|
-
catch {
|
|
58
|
-
return String(number);
|
|
59
|
-
}
|
|
60
|
-
};
|
|
61
|
-
const formatNumberCompact = (number, { decimals = 0, forceLatin = true, numberFormatOptions = {} } = {}) => {
|
|
62
|
-
try {
|
|
63
|
-
const formatter = numberFormatCompact({
|
|
64
|
-
browserSafeLocale: getBrowserSafeLocale(),
|
|
65
|
-
decimals,
|
|
66
|
-
forceLatin,
|
|
67
|
-
numberFormatOptions,
|
|
68
|
-
});
|
|
69
|
-
return formatter.format(number);
|
|
70
|
-
}
|
|
71
|
-
catch {
|
|
72
|
-
return String(number);
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
const formatCurrency = (number, currency, { stripZeros = false, isSmallestUnit = false, signForPositive = false, forceLatin = true } = {}) => {
|
|
76
|
-
return numberFormatCurrency({
|
|
77
|
-
number,
|
|
78
|
-
currency,
|
|
79
|
-
browserSafeLocale: getBrowserSafeLocale(),
|
|
80
|
-
stripZeros,
|
|
81
|
-
isSmallestUnit,
|
|
82
|
-
signForPositive,
|
|
83
|
-
geoLocation: geoLocationState,
|
|
84
|
-
forceLatin,
|
|
85
|
-
currencyOverrides: currencyOverridesState,
|
|
86
|
-
});
|
|
87
|
-
};
|
|
88
|
-
const getCurrencyObject = (number, currency, { stripZeros = false, isSmallestUnit = false, signForPositive = false, forceLatin = true } = {}) => {
|
|
89
|
-
return getCurrencyObjectFromCurrencyFormatter({
|
|
90
|
-
number,
|
|
91
|
-
currency,
|
|
92
|
-
browserSafeLocale: getBrowserSafeLocale(),
|
|
93
|
-
stripZeros,
|
|
94
|
-
isSmallestUnit,
|
|
95
|
-
signForPositive,
|
|
96
|
-
geoLocation: geoLocationState,
|
|
97
|
-
forceLatin,
|
|
98
|
-
currencyOverrides: currencyOverridesState,
|
|
99
|
-
});
|
|
100
|
-
};
|
|
101
|
-
return {
|
|
102
|
-
setLocale,
|
|
103
|
-
setGeoLocation,
|
|
104
|
-
setCurrencyOverrides,
|
|
105
|
-
formatNumber,
|
|
106
|
-
formatNumberCompact,
|
|
107
|
-
formatCurrency,
|
|
108
|
-
getCurrencyObject,
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
export default createNumberFormatters;
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import debugFactory from 'debug';
|
|
2
|
-
import { FALLBACK_LOCALE } from "./constants.js";
|
|
3
|
-
const debug = debugFactory('number-formatters:get-cached-formatter');
|
|
4
|
-
const formatterCache = new Map();
|
|
5
|
-
/**
|
|
6
|
-
* Get a cached formatter for a given locale and options.
|
|
7
|
-
* @param params - The parameters for the formatter.
|
|
8
|
-
* @param params.locale - The locale to format the number in.
|
|
9
|
-
* @param params.options - Intl.NumberFormatOptions to pass to the formatter.
|
|
10
|
-
* @param params.fallbackLocale - The locale to fallback to if the locale is not supported.
|
|
11
|
-
* @param params.retries - The number of retries to attempt if the formatter is not created.
|
|
12
|
-
* @return {Intl.NumberFormat} A cached formatter for the given locale and options.
|
|
13
|
-
*/
|
|
14
|
-
export function getCachedFormatter({ locale, fallbackLocale = FALLBACK_LOCALE, options, retries = 1, }) {
|
|
15
|
-
const cacheKey = JSON.stringify([locale, options]);
|
|
16
|
-
try {
|
|
17
|
-
return (formatterCache.get(cacheKey) ??
|
|
18
|
-
formatterCache.set(cacheKey, new Intl.NumberFormat(locale, options)).get(cacheKey));
|
|
19
|
-
}
|
|
20
|
-
catch (error) {
|
|
21
|
-
// If the locale is invalid, creating the NumberFormat will throw.
|
|
22
|
-
debug(`Intl.NumberFormat was called with a non-existent locale "${locale}"; falling back to ${fallbackLocale}`);
|
|
23
|
-
if (retries) {
|
|
24
|
-
return getCachedFormatter({
|
|
25
|
-
locale: fallbackLocale,
|
|
26
|
-
options,
|
|
27
|
-
retries: retries - 1,
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
throw error;
|
|
31
|
-
}
|
|
32
|
-
}
|
package/dist/esm/index.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import createNumberFormatters from "./create-number-formatters.js";
|
|
2
|
-
const defaultFormatter = createNumberFormatters();
|
|
3
|
-
export const { setLocale, setGeoLocation, setCurrencyOverrides, formatNumber, formatNumberCompact, formatCurrency, getCurrencyObject, } = defaultFormatter;
|
|
4
|
-
export { createNumberFormatters };
|
|
5
|
-
// We can optionally export the formatters individually if we want to use them in a more granular way.
|
|
6
|
-
// export { numberFormat, numberFormatCompact, numberFormatCurrency, getCurrencyObject };
|