currency.ts 653 B

12345678910111213141516171819202122232425262728
  1. import getMeta from '@/utils/meta'
  2. const DEFAULT_LOCALE = getMeta('ol-i18n')?.currentLangCode ?? 'en'
  3. export function formatCurrency(
  4. amount: number,
  5. currency: string,
  6. locale: string = DEFAULT_LOCALE,
  7. stripIfInteger = false
  8. ): string {
  9. const options: Intl.NumberFormatOptions = { style: 'currency', currency }
  10. if (stripIfInteger && Number.isInteger(amount)) {
  11. options.minimumFractionDigits = 0
  12. }
  13. try {
  14. return amount.toLocaleString(locale, {
  15. ...options,
  16. currencyDisplay: 'narrowSymbol',
  17. })
  18. } catch {}
  19. try {
  20. return amount.toLocaleString(locale, options)
  21. } catch {}
  22. return `${currency} ${amount}`
  23. }