currency.ts 745 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. export type CurrencyCode =
  2. | 'AUD'
  3. | 'BRL'
  4. | 'CAD'
  5. | 'CHF'
  6. | 'CLP'
  7. | 'COP'
  8. | 'DKK'
  9. | 'EUR'
  10. | 'GBP'
  11. | 'INR'
  12. | 'MXN'
  13. | 'NOK'
  14. | 'NZD'
  15. | 'PEN'
  16. | 'SEK'
  17. | 'SGD'
  18. | 'USD'
  19. export function formatCurrencyLocalized(
  20. amount: number,
  21. currency: CurrencyCode,
  22. locale: string,
  23. stripIfInteger = false
  24. ): string {
  25. const options: Intl.NumberFormatOptions = { style: 'currency', currency }
  26. if (stripIfInteger && Number.isInteger(amount)) {
  27. options.minimumFractionDigits = 0
  28. }
  29. try {
  30. return amount.toLocaleString(locale, {
  31. ...options,
  32. currencyDisplay: 'narrowSymbol',
  33. })
  34. } catch {}
  35. try {
  36. return amount.toLocaleString(locale, options)
  37. } catch {}
  38. return `${currency} ${amount}`
  39. }