Просмотр исходного кода

[web] Handle error cause by `currencyDisplay: 'narrowSymbol'` in old browsers (#18060)

* Handle error cause by `currencyDisplay: 'narrowSymbol'` in old browsers

RangeError
Value narrowSymbol out of range for Number.prototype.toLocaleString options property currencyDisplay

* Make `formatCurrencyLocalized` bulletproof

GitOrigin-RevId: 26e8abc6f9fb7c06c2d14b9d86af2d84fb9f32e3
Antoine Clausse 2 лет назад
Родитель
Сommit
e32b4f0db1

+ 13 - 9
services/web/app/src/util/currency.js

@@ -14,19 +14,23 @@
  * @returns {string}
  */
 function formatCurrencyLocalized(amount, currency, locale, stripIfInteger) {
+  const options = { style: 'currency', currency }
   if (stripIfInteger && Number.isInteger(amount)) {
+    options.minimumFractionDigits = 0
+  }
+
+  try {
     return amount.toLocaleString(locale, {
-      style: 'currency',
-      currency,
-      minimumFractionDigits: 0,
+      ...options,
       currencyDisplay: 'narrowSymbol',
     })
-  }
-  return amount.toLocaleString(locale, {
-    style: 'currency',
-    currency,
-    currencyDisplay: 'narrowSymbol',
-  })
+  } catch {}
+
+  try {
+    return amount.toLocaleString(locale, options)
+  } catch {}
+
+  return `${currency} ${amount}`
 }
 
 module.exports = {

+ 13 - 9
services/web/frontend/js/shared/utils/currency.ts

@@ -23,17 +23,21 @@ export function formatCurrencyLocalized(
   locale: string,
   stripIfInteger = false
 ): string {
+  const options: Intl.NumberFormatOptions = { style: 'currency', currency }
   if (stripIfInteger && Number.isInteger(amount)) {
+    options.minimumFractionDigits = 0
+  }
+
+  try {
     return amount.toLocaleString(locale, {
-      style: 'currency',
-      currency,
-      minimumFractionDigits: 0,
+      ...options,
       currencyDisplay: 'narrowSymbol',
     })
-  }
-  return amount.toLocaleString(locale, {
-    style: 'currency',
-    currency,
-    currencyDisplay: 'narrowSymbol',
-  })
+  } catch {}
+
+  try {
+    return amount.toLocaleString(locale, options)
+  } catch {}
+
+  return `${currency} ${amount}`
 }