How to format numbers similar to Stack Overflow reputation format

前端 未结 8 955
我在风中等你
我在风中等你 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:27

    UPDATE: CMS got the check and provides a superior answer. Send any more votes his way.

    // 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();
    }
    

    Output:

    • getRepString(999) == '999'
    • getRepString(1000) == '1,000'
    • getRepString(9999) == '9,999'
    • getRepString(10000) == '10k'
    • getRepString(10100) == '10.1k'
    0 讨论(0)
  • 2020-11-27 07:29

    Here is a function in PHP which is part of iZend - http://www.izend.org/en/manual/library/countformat:

    function count_format($n, $point='.', $sep=',') {
        if ($n < 0) {
            return 0;
        }
    
        if ($n < 10000) {
            return number_format($n, 0, $point, $sep);
        }
    
        $d = $n < 1000000 ? 1000 : 1000000;
    
        $f = round($n / $d, 1);
    
        return number_format($f, $f - intval($f) ? 1 : 0, $point, $sep) . ($d == 1000 ? 'k' : 'M');
    }
    
    0 讨论(0)
提交回复
热议问题