如何格式化类似Stack Overflow信誉格式的数字

Sky*_*ers 14 javascript number-formatting

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

例如

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

CMS*_*CMS 26

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

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';
}
Run Code Online (Sandbox Code Playgroud)

此处检查输出结果.


Sky*_*ers 10

更新:CMS得到了检查,并提供了一个很好的答案.以他的方式发送更多选票.

// formats a number similar to the way stack exchange sites 
// format reputation. e.g.
// for numbers< 10000 the output is '9,999'
// for numbers > 10000 the output is '10k' with one decimal place when needed
function getRepString(rep)
{
    var repString;

    if (rep < 1000)
    {
        repString = rep;
    }
    else if (rep < 10000)
    {
        // removed my rube goldberg contraption and lifted
        // CMS version of this segment
        repString = rep.charAt(0) + ',' + rep.substring(1);
    }
    else
    {
        repString = (Math.round((rep / 1000) * 10) / 10) + "k"
    }

    return repString.toString();
}
Run Code Online (Sandbox Code Playgroud)

输出:

  • getRepString(999) =='999'
  • getRepString(1000) =='1,000'
  • getRepString(9999) =='9,999'
  • getRepString(10000) =='10k'
  • getRepString(10100) == '10 .1k'