JavaScript & V8 Internals (536 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)
How do you format large numbers with compact metric suffixes (e.g., 1.2K, 3.4M) without external libraries?
mid LevelCode ExampleFormsPerformanceHTTP & REST APIs
Social platforms (YouTube views, GitHub stars, Twitter followers) display abbreviated numbers (e.g., 1200 → "1.2K", 1500000 → "1.5M").
1. Native Modern Solution: Intl.NumberFormat
javascript
function formatCompactNative(num) {
return new Intl.NumberFormat('en-US', {
notation: 'compact',
compactDisplay: 'short',
maximumFractionDigits: 1
}).format(num);
}
console.log(formatCompactNative(1250)); // "1.3K"
console.log(formatCompactNative(1500000)); // "1.5M"
console.log(formatCompactNative(2400000000)); // "2.4B"
2. Custom Polyfill / Algorithm (Frequently Tested in Coding Screens)
When interviewers require implementing this manually without Intl.NumberFormat:
javascript
function formatCompactManual(num, decimals = 1) {
if (num === 0) return "0";
const isNegative = num < 0;
const absNum = Math.abs(num);
if (absNum < 1000) return (isNegative ? "-" : "") + absNum;
const suffixes = ["", "K", "M", "B", "T"];
// Determine exponent tier (0 for <1K, 1 for K, 2 for M, 3 for B, etc.)
const tier = Math.floor(Math.log10(absNum) / 3);
// Clamp tier to maximum available suffix
const actualTier = Math.min(tier, suffixes.length - 1);
const scale = Math.pow(10, actualTier * 3);
const scaledNum = absNum / scale;
// Format to decimal places and remove trailing zero if integer (e.g. 1.0K -> 1K)
const formatted = scaledNum.toFixed(decimals).replace(/\.0$/, "");
const result = formatted + suffixes[actualTier];
return isNegative ? `-${result}` : result;
}
console.log(formatCompactManual(999)); // "999"
console.log(formatCompactManual(1200)); // "1.2K"
console.log(formatCompactManual(1000000)); // "1M"
console.log(formatCompactManual(2550000, 2)); // "2.55M"
console.log(formatCompactManual(-54300)); // "-54.3K"