How to format a number as 2.5K if a thousand or more, otherwise 900 in javascript?
I need to show a currency value in the format of 1K of equal to one thousand, or 1.1K, 1.2K, 1.9K etc, if its not an even thousands, otherwise if under a thousand, display normal 500, 100, 250 etc, using javascript to format the number?
formatting
Javascript
jQuery
numbers
- asked 8 years ago
- Gul Hafiz
3Answer
Sounds like this should work for you:
function kFormatter(num) {
return num > 999 ? (num/1000).toFixed(1) + 'k' : num
}
console.log(kFormatter(1200));
console.log(kFormatter(900));
- answered 8 years ago
- B Butts
Further improving Salman's Answer because it returns nFormatter(33000) as 33.0K
function nFormatter(num) {
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
}
return num;
}
now nFormatter(33000) = 33K
- answered 8 years ago
- G John
A more general version:
function nFormatter(num, digits) {
var si = [
{ value: 1E18, symbol: "E" },
{ value: 1E15, symbol: "P" },
{ value: 1E12, symbol: "T" },
{ value: 1E9, symbol: "G" },
{ value: 1E6, symbol: "M" },
{ value: 1E3, symbol: "k" }
], i;
for (i = 0; i < si.length; i++) {
if (num >= si[i].value) {
return (num / si[i].value).toFixed(digits).replace(/\.?0+$/, "") + si[i].symbol;
}
}
return num;
}
console.log(nFormatter(123, 1)); // 123
console.log(nFormatter(1234, 1)); // 1.2k
console.log(nFormatter(100000000, 1)); // 100M
console.log(nFormatter(299792458, 1)); // 299.8M
- answered 8 years ago
- Gul Hafiz
Your Answer