addCommas (v2)

Revision 2 of this benchmark created by Ryan Sullivan on


Description

addCommas is a simple script to add commas at every 3 digits from the right.

'Mine' supports both numbers and strings as an argument.

'Theirs' comes from mredkj.com, variations of which I have seen all over.

Test runner

Ready to run.

Testing in
TestOps/sec
Mine
var addCommas = function(n) {
 var digits, s = +n + '';
 if (s.indexOf('e') > -1) {
  x = s.split('e');
  if (+x[1] < 0) {
   return n;
  }
  s = x[0].replace('.', '');
  s += new Array(+x[1] + 2 - s.length).join('0');
  digits = s.length;
 } else {
  digits = (Math.floor(+n) + '').length;
 }
 for (var i = 0, j = 0, mod = digits % 3; i < digits; i++) {
  if (s[i + j] == '.') {
   break;
  }
  if (i == 0 || i % 3 != mod) {
   continue;
  }
  s = s.substr(0, i + j) + ',' + s.substr(i + j);
  j++;
 }
 return s;
};
addCommas(333000000000000000000) // 3.33e20
ready
Theirs
function addCommas(nStr) {
 nStr += '';
 x = nStr.split('.');
 x1 = x[0];
 x2 = x.length > 1 ? '.' + x[1] : '';
 var rgx = /(\d+)(\d{3})/;
 while (rgx.test(x1)) {
  x1 = x1.replace(rgx, '$1' + ',' + '$2');
 }
 return x1 + x2;
}
addCommas(333000000000000000000) // 3.33e20
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Ryan Sullivan on
  • Revision 2: published by Ryan Sullivan on
  • Revision 3: published by Ryan Sullivan on
  • Revision 9: published by Scott Sauyet on
  • Revision 10: published by dexbol on