Number formatting with commas

JavaScript performance comparison

Revision 25 of this test case created by

Preparation code

<script>
var number = 343535353.53880934, v;

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 parts(num){
    var s = num + '', i = s.length, bits = [], cur = '';
    while(i--){
        cur = s.charAt(i) + cur;
        if(cur.length === 3 || i === 0){ bits.unshift(cur); cur = ''; }
    }
    return bits.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] 
}

function myCommafy(num){
    var s = num + '', i = l = s.length, res = '';
    while(i--){
        res = (i == 0 ? '' : (l - i) % 3 ? '' : ',') + s.charAt(i) + res;
    }
    return res;
}
</script>
    

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
commafy
v= commafy(number);
pending…
parts
v= parts(number);
pending…
my commafy
v= myCommafy(number);
pending…

Compare results of other browsers

Revisions

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

0 Comments