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