src/utils/formatters.ts (view raw)
1// Format large numbers for display
2export const formatNumber = (num: number): string => {
3 if (num === 0) return '0';
4
5 const suffixes = ['', 'K', 'M', 'B', 'T', 'Qa', 'Qi', 'Sx', 'Sp', 'Oc', 'No', 'Dc'];
6
7 // For very small numbers, just return the number
8 if (num < 1) return num.toFixed(2);
9
10 // For numbers less than 1000, show them as is
11 if (num < 1000) return num.toFixed(0);
12
13 // Find the suffix index
14 const suffixIndex = Math.floor(Math.log10(num) / 3);
15
16 if (suffixIndex >= suffixes.length) {
17 // For extremely large numbers, use scientific notation
18 return num.toExponential(2);
19 }
20
21 // Format with the appropriate suffix
22 const scaledNum = num / Math.pow(10, suffixIndex * 3);
23
24 // For numbers like 1000-9999, show one decimal place
25 // For larger numbers, show two decimal places
26 const decimalPlaces = scaledNum < 10 ? 1 : 0;
27
28 return scaledNum.toFixed(decimalPlaces) + suffixes[suffixIndex];
29};