如何格式化类似Stack Overflow信誉格式的数字 [英] How to format numbers similar to Stack Overflow reputation format

查看:157
本文介绍了如何格式化类似Stack Overflow信誉格式的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数字转换为字符串表示形式,其格式类似于Stack Overflow信誉显示。

I want to convert a number into a string representation with a format similar to Stack Overflow reputation display.

例如


  • 999 =='999'

  • 1000 =='1,000'

  • 9999 =='9,999 '

  • 10000 =='10k'

  • 10100 == '10 .1k'

  • 999 == '999'
  • 1000 == '1,000'
  • 9999 == '9,999'
  • 10000 == '10k'
  • 10100 == '10.1k'

推荐答案

另一种产生所需输出的方法:

Another approach that produces exactly the desired output:

function getRepString (rep) {
  rep = rep+''; // coerce to string
  if (rep < 1000) {
    return rep; // return the same number
  }
  if (rep < 10000) { // place a comma between
    return rep.charAt(0) + ',' + rep.substring(1);
  }
  // divide and format
  return (rep/1000).toFixed(rep % 1000 != 0)+'k';
}

检查输出结果这里

这篇关于如何格式化类似Stack Overflow信誉格式的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆