All files / app/i18n numbers.ts

100% Statements 12/12
100% Branches 4/4
100% Functions 2/2
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 316x     6x       229x 229x 229x 229x 8x 8x   229x       229x     229x 229x                
import { toFormatLocale } from "i18n/locales";
 
// Creating Intl.NumberFormat every time is slow, so cache one per locale+options.
const intlNumberFormatCache = new Map<string, Intl.NumberFormat>();
 
/** Gets a cached Intl.NumberFormat, applying our locale -> format-locale mapping. */
function getIntlNumberFormat(locale: string, options?: Intl.NumberFormatOptions): Intl.NumberFormat {
  const formatLocale = toFormatLocale(locale);
  const cacheKey = JSON.stringify({ ...options, locale: formatLocale });
  let format = intlNumberFormatCache.get(cacheKey);
  if (!format) {
    format = new Intl.NumberFormat(formatLocale, options);
    intlNumberFormatCache.set(cacheKey, format);
  }
  return format;
}
 
/** Localizes a USD amount, e.g. "$1,234" / "1.234 $" depending on locale. */
export function localizeUSD(amount: number, locale: string): string {
  // Show cents (always 2 digits) only when the amount actually has a fractional part,
  // e.g. 1 -> "$1", 1.1 -> "$1.10", 1.11 -> "$1.11".
  const hasCents = !Number.isInteger(amount);
  return getIntlNumberFormat(locale, {
    style: "currency",
    currency: "USD",
    currencyDisplay: "narrowSymbol",
    minimumFractionDigits: hasCents ? 2 : 0,
    maximumFractionDigits: 2,
  }).format(amount);
}