Files
HiveGrid-Wireframes/hivegrid-cloud/packages/i18n/src/intl/number.ts
T

25 lines
1.3 KiB
TypeScript

// Locale-aware number formatter wrapping `Intl.NumberFormat`. Centralised so
// every callsite shares a single contract — decimal/percent/compact derive
// from this helper to avoid drift between server/client.
import { getCachedFormatter } from "./cache.js";
export type FormatNumberOptions = Intl.NumberFormatOptions & { locale: string };
const numberFormatters = new Map<string, Intl.NumberFormat>();
export function formatNumber(value: number, options: FormatNumberOptions): string {
const { locale, ...rest } = options;
return getCachedFormatter(numberFormatters, locale, rest, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
}
export function formatPercent(value: number, options: FormatNumberOptions): string {
const { locale, ...rest } = options;
return getCachedFormatter(numberFormatters, locale, { style: "percent", ...rest }, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
}
export function formatCompactNumber(value: number, options: FormatNumberOptions): string {
const { locale, ...rest } = options;
return getCachedFormatter(numberFormatters, locale, { notation: "compact", ...rest }, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
}