overleaf/services/web/frontend/js/shared/utils/currency.ts
Antoine Clausse e32b4f0db1 [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
2024-04-26 08:04:22 +00:00

43 lines
745 B
TypeScript

export type CurrencyCode =
| 'AUD'
| 'BRL'
| 'CAD'
| 'CHF'
| 'CLP'
| 'COP'
| 'DKK'
| 'EUR'
| 'GBP'
| 'INR'
| 'MXN'
| 'NOK'
| 'NZD'
| 'PEN'
| 'SEK'
| 'SGD'
| 'USD'
export function formatCurrencyLocalized(
amount: number,
currency: CurrencyCode,
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, {
...options,
currencyDisplay: 'narrowSymbol',
})
} catch {}
try {
return amount.toLocaleString(locale, options)
} catch {}
return `${currency} ${amount}`
}