Number formatting with commas (v5)

Revision 5 of this benchmark created by runsun on


Preparation HTML

<script>
var number = 343535353.53880934, v;

function formatNumber(num) {
  var decimalPart = '';
  num = ''+num;
  if (num.indexOf('.') != -1) {
    decimalPart = '.' + num.split('.')[1];
    num = parseInt(num.split('.')[0]);
  }
  var array = (''+num).split('');
  var index = -3;
  while (array.length + index > 0) {
    array.splice(index, 0, ',');
    index -= 4;
  }
  return array.join('') + decimalPart;
};

function formatNumberRgx(num) {
  var parts = (''+num).split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join(".");
};

function commafy( num){
  var parts = (''+num).split("."), s=parts[0], i=L= s.length, o='',c;
  while(i--){ o = (i==0?'':((L-i)%3?'':',')) 
                 +s.charAt(i) +o }
  return o+'.'+parts[1] 
}

// commafy2: add "," to decimal part, too
function commafy2(num){  
  var parts = (''+num).split("."), s=parts[0], i=L= s.length, o='',c;
  while(i--){ o = (i==0?'':((L-i)%3?'':',')) 
                 +s.charAt(i) +o }
  o+='.'; s= parts[1]; i=L=s.length;
  while(i--){ o += s.charAt(i) +(i==0?'':((L-i)%3?'':',')) 
                  }
  return o 
}

function commafyandround( num){
  var parts = num.toFixed(2).split("."), s=parts[0], i=L= s.length, o='',c;
  while(i--){ o = (i==0?'':((L-i)%3?'':',')) 
                 +s.charAt(i) +o }
  return o+'.'+parts[1] 
}


ui.events.start.push( function(){ 
                      console.log('\n\n Testing start, number='
                                 + number+'\n\n' ) } )

for( var i=0, tcase; tcase=ui.benchmarks[i]; i++ )
{
     if(window.console) tcase.events.complete=[
       function(){
                this.funcReturn = v; 
                console.log( '== test #'+ this.id
                + ' ('+ this.name + ') complete'
                + ', v= '+ v
                )
       }
     ]   
} 

ui.events.complete.push(
   function(){
      console.log('\n\n Result:\n'  );
      var tcases = ui.benchmarks;
      var out= Array( tcases.length );
      for( var i=0, tcase; tcase=tcases[i]; i++ )
      {
         console.log( tcase.name + ' = '
                    + tcase.funcReturn + ', ops/sec= '
                    + commafy( (''+tcase.hz).replace(/^\s*/,'')).split('.')[0]
                    )
      }
   }
)

function numberWithCommas(x) {
    return (""+x).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

</script>

Test runner

Ready to run.

Testing in
TestOps/sec
1. without regex
v= formatNumber(number);
ready
2. with regex
v= formatNumberRgx(number);
ready
3. toLocaleString
v= number.toLocaleString();
ready
4. commafy
v= commafy(number);
ready
5. commafyandround
v= commafyandround(number);
ready
6. StackOverflow numberWithCommas
v= numberWithCommas(number);
ready
7. commafy2
v= commafy2(number);
ready

Revisions

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