formatPrice (utils/format-price.ts)

airi · server/apps/api/src/utils/format-price.ts · typescript · MIT
payments

Formats a smallest-unit amount into a locale‑aware currency string.

// Source: https://github.com/moeru-ai/airi | License: MIT | Copyright 2024-PRESENT Neko Ayaka
// Provided via justclaw.it.com; keep this notice with the code.
/**
 * Formats a smallest-unit amount into a display price string.
 *
 * @example
 * formatPrice(300, 'usd')
 * // => '$3.00'
 */
export function formatPrice(unitAmount: number | null, currency: string): string {
  if (unitAmount == null)
    return currency.toUpperCase()

  try {
    const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency })
    const fractionDigits = formatter.resolvedOptions().minimumFractionDigits ?? 2
    return formatter.format(unitAmount / (10 ** fractionDigits))
  }
  catch {
    return `${unitAmount / 100} ${currency.toUpperCase()}`
  }
}

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key