Approach 1: Built-in library
I would recommend using Javascript’s built-in library method Intl.NumberFormat
Intl.NumberFormat('en-US', {
notation: "compact",
maximumFractionDigits: 1
}).format(2500);
Approach 2: No library
But you can also create these abbreviations with simple if
statements, and without the complexity of Math
, maps
, regex
, for
-loops, etc.
Formatting Cash value with K
const formatCash = n => {
if (n < 1e3) return n;
if (n >= 1e3) return +(n / 1e3).toFixed(1) + "K";
};
console.log(formatCash(2500));
Formatting Cash value with K M B T
const formatCash = n => {
if (n < 1e3) return n;
if (n >= 1e3 && n < 1e6) return +(n / 1e3).toFixed(1) + "K";
if (n >= 1e6 && n < 1e9) return +(n / 1e6).toFixed(1) + "M";
if (n >= 1e9 && n < 1e12) return +(n / 1e9).toFixed(1) + "B";
if (n >= 1e12) return +(n / 1e12).toFixed(1) + "T";
};
console.log(formatCash(1235000));
Using negative numbers
let format;
const number = -1235000;
if (number < 0) {
format="-" + formatCash(-1 * number);
} else {
format = formatCash(number);
}