【问题标题】:Get short followers count without rounding up in javascript无需在 javascript 中四舍五入即可获得短关注者数量
【发布时间】:2021-01-31 16:02:06
【问题描述】:

我想缩短精确数量的追随者,并像社交平台一样以一种很好的方式展示它。问题是我的代码正在四舍五入最后一位。

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

如果我将 Math.round 除以 100 而不是 10,我会阻止向上舍入,但会得到两位小数,这是不需要的。

【问题讨论】:

  • 使用Math.floor 代替Math.round?

标签: javascript math social-media


【解决方案1】:

像这样试试。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多