currency.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. }
  24. export function convertToMinorUnits(amount: number, currency: string): number {
  25. const isNoCentsCurrency = ['clp', 'jpy', 'krw', 'vnd'].includes(
  26. currency.toLowerCase()
  27. )
  28. // Determine the multiplier based on currency
  29. let multiplier = 100 // default for most currencies (2 decimal places)
  30. if (isNoCentsCurrency) {
  31. multiplier = 1 // no decimal places
  32. }
  33. // Convert and round to an integer
  34. return Math.round(amount * multiplier)
  35. }