I want to short a precise number of followers and display it in a nice way like the social platforms. The problem is that my code is rounding up the last digit.
function getShortFollowers(num){
function intlFormat(num){
return new Intl.NumberFormat().format(Math.round(num*10)/10);
}
if(num >= 1000000)
return intlFormat(num/1000000)+'M';
if(num >= 1000)
return intlFormat(num/1000)+'k';
return intlFormat(num);
}
// Result
console.log(getShortFollowers(28551) // output: 28.6
// Wanted result
console.log(getShortFollowers(28551) // output: 28.5
If I divide Math.round with 100 instead of 10 I prevent the rounding up but get two digit decimal, which is unwanted.
try like this.
function getShortFollowers(num){
function intlFormat(num){
return new Intl.NumberFormat().format(Math.floor(num*10)/10);
}
if(num >= 1000000)
return intlFormat(num/1000000)+'M';
if(num >= 1000)
return intlFormat(num/1000)+'k';
return intlFormat(num);
}
// Result
console.log(getShortFollowers(28551)) // output: 28.5k