JavaScript function named formatNumber that takes a number as input and formats it using the “K”, “M”, “B”, “T” abbreviations for thousands, millions, billions, and trillions respectively.
const formatNumber = (number) => {
if (number === 0) {
return "0";
}
const abbreviations =
['', 'K', 'M', 'B', 'T', 'Q', 'QQ', 'QQQ', 'QQQQ'];
const sign = number < 0 ? "-" : "";
number = Math.abs(number);
let index = 0;
while (number >= 1000 && index < abbreviations.length - 1) {
number /= 1000;
index++;
}
const roundedNumber = Math.round(number * 100) / 100;
const formattedNumber = Number.isInteger(roundedNumber)
? roundedNumber.toFixed(0)
: roundedNumber.toFixed(2);
return `${sign}${formattedNumber}${abbreviations[index]}`;
};
console.log(formatNumber(1234)); // Output: 1.23K
console.log(formatNumber(1234567)); // Output: 1.23M
console.log(formatNumber(1234567890)); // Output: 1.23B
console.log(formatNumber(1234567890123)); // Output: 1.23T
console.log(formatNumber(-987654321)); // Output: -988M
console.log(formatNumber(0.000123)); // Output: 0
More Easy way
let num = 23423423423;
const formatter = Intl.NumberFormat("en", { notation: "compact" });
console.log( formatter.format(num));