my pkgs monorepo
1function getLocale(locale?: string): string {
2 return locale || (typeof navigator !== 'undefined' && navigator.language) || 'en-GB';
3}
4
5export function formatCompactNumber(num?: number, locale?: string): string {
6 if (num === undefined || num === null) return '0';
7 const effectiveLocale = getLocale(locale);
8 if (num >= 1000) {
9 const divisor = num >= 1000000000 ? 1000000000 : num >= 1000000 ? 1000000 : 1000;
10 const roundedDown = Math.floor((num / divisor) * 10) / 10;
11 const adjustedNum = roundedDown * divisor;
12 return new Intl.NumberFormat(effectiveLocale, {
13 notation: 'compact',
14 compactDisplay: 'short',
15 maximumFractionDigits: 1
16 }).format(adjustedNum);
17 }
18 return new Intl.NumberFormat(effectiveLocale, {
19 notation: 'compact',
20 compactDisplay: 'short',
21 maximumFractionDigits: 1
22 }).format(num);
23}
24
25export function formatNumber(num: number, locale?: string): string {
26 return new Intl.NumberFormat(getLocale(locale)).format(num);
27}