Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format numbers similar to Stack Overflow reputation format

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

e.g.

  • 999 == '999'
  • 1000 == '1,000'
  • 9999 == '9,999'
  • 10000 == '10k'
  • 10100 == '10.1k'
like image 246
Sky Sanders Avatar asked Jul 05 '10 07:07

Sky Sanders


People also ask

How do I start an answer on stackoverflow?

Answering Questions. Go to https://stackoverflow.com/questions. You can use any web browser, like Chrome or Safari, to visit this site and answer questions. You can sort the questions by newest, active, bountied, unanswered, and more.


2 Answers

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.

like image 50
Christian C. Salvadó Avatar answered Oct 21 '22 09:10

Christian C. Salvadó


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'
like image 29
Sky Sanders Avatar answered Oct 21 '22 08:10

Sky Sanders