• support@answerspoint.com

How to format a number as 2.5K if a thousand or more, otherwise 900 in javascript?

6085

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?

3Answer


0

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

0

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

0

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

    Facebook Share        
       
  • asked 8 years ago
  • viewed 6085 times
  • active 8 years ago

Best Rated Questions