Number formatting with commas

JavaScript performance comparison

Revision 20 of this test case created by SMM

Preparation code

<script>
var number = -1013.86, v;

function noop(num) {
  return ''+num;
}

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, ",");
}

function insertCommas(str)
{
    var a = (str+'').split("");
    a.reverse();

    var t, i = 0, arr = Array();

    while (t = a.shift())
    {
       if (((i++ % 3) == 0) && arr.length > 0)
           arr.unshift(",");
       arr.unshift(t);
    }

    return arr.join("");
}


var number_format = function(number, decimal_pos, decimal_sep, thousand_sep) {
    var ts      = ( thousand_sep == null ? ',' : thousand_sep )
        , ds    = ( decimal_sep  == null ? '.' : decimal_sep )
        , dp    = ( decimal_pos  == null ? 2   : decimal_pos )

        , n     = Math.abs(Math.ceil(number)).toString()

        , i     = n.length % 3 
        , f     = n.substr(0, i)
    ;

    if(number < 0) f = '-' + f;

    for(;i<n.length;i+=3) {
        if(i!=0) f+=ts;
        f+=n.substr(i,3);
    }

    if(dp > 0) 
        f += ds + number.toFixed(dp).split('.')[1]

    return f;
}

</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
7. commafy2
v= commafy2(number);
pending…
SO answer #2
v = insertCommas(number);
pending…
SO answer #3
v = number_format(number) ;
pending…
NOOP baseline
v = noop(number);
pending…
1. without regex
v= formatNumber(number);
pending…
2. with regex
v= formatNumberRgx(number);
pending…
3. toLocaleString
v= number.toLocaleString();
pending…
4. commafy
v= commafy(number);
pending…
5. commafyandround
v= commafyandround(number);
pending…
6. StackOverflow numberWithCommas
v= numberWithCommas(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