1

I fetch around 1000 different numbers from a CMS to display them in my frontend. I want to display anything above 1000 as 1k and so on. There are only full numbers fetched and no decimals. Few examples: 1200 = 1.2k, 1209 = 1.2k, 18094 = 18.1k 999 = 999

So in the first place i have to check every number if it has more than 3 digits, if so it should round correctly and after it append a "k" to the number (now string in this case). The first step is clear to me but i struggle a bit with the correct rounding. The solution should also be as most cost efficient as possible. The solution needs to be in JS.

Maybe someone can help me out, thanks in advance!

Alex
  • 132
  • 1
  • 4
  • 21
  • Hi You can try http://numeraljs.com/ – Techie Feb 24 '21 at 09:13
  • Does this answer your question? [Javascript: formatting a rounded number to N decimals](https://stackoverflow.com/questions/2221167/javascript-formatting-a-rounded-number-to-n-decimals) – einord Feb 24 '21 at 09:38

2 Answers2

1

Convert to Number, if > 1000 divide by 1000 and use Number.toFixed to display

["22", "13421"].forEach( n => console.log(+n > 1000 ? `${(+n/1000).toFixed(1)}k` : n) );
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

For rounding, after dividing, use toFixed to take only one digit after .

  • num = (num/1000).toFixed(1);

Add the details code here,

//test run data
let nums = [10,10,100,1000,2000,2220];
//just for printing
let numString = '';
//you can store in another or ...

nums.forEach(converter);

function converter(num){
  if(num >= 1000){
    num = (num/1000).toFixed(1);
    numString = num+ 'k';
  }else{
    numString = num+'';
  }
  console.log(numString);
}
Md Kawser Habib
  • 1,966
  • 2
  • 10
  • 25