How to format numbers similar to Stack Overflow reputation format

前端 未结 8 992
我在风中等你
我在风中等你 2020-11-27 06:41

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

e.g.

  • 999 == \'999\'
  • 1000 =
8条回答
  •  温柔的废话
    2020-11-27 07:09

    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';
    }
    

    Check the output results here.

提交回复
热议问题