Left zero pad

JavaScript performance comparison

Test case created

Info

Belonging to this question on StackOverflow.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var numsToPad=[[1,100],[-123,4],[5.619,7],[1234567890,2]];
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Peter Bailey's
function f(n,w){
  w-=n.toString().length;
  if(w>0)return new Array(w+(/\./.test(n)?2:1)).join('0')+n;
  return str=n+"";
}
f(numsToPad[0][0],numsToPad[0][1]);
f(numsToPad[1][0],numsToPad[1][1]);
f(numsToPad[2][0],numsToPad[2][1]);
f(numsToPad[3][0],numsToPad[3][1]);
pending…
profitehlolz's
function f(n,w){
  var pad=new Array(1+w).join('0');
  return (pad+n).slice(-pad.length);
}
f(numsToPad[0][0],numsToPad[0][1]);
f(numsToPad[1][0],numsToPad[1][1]);
f(numsToPad[2][0],numsToPad[2][1]);
f(numsToPad[3][0],numsToPad[3][1]);
pending…
coderjoe's
function f(n,w){
  var n_ = Math.abs(n);
        var zeros = Math.max(0, w - Math.floor(n_).toString().length );
        var zeroString = Math.pow(10,zeros).toString().substr(1);
        if( n < 0 ) {
                zeroString = '-' + zeroString;
        }

  return zeroString+n;
}
f(numsToPad[0][0],numsToPad[0][1]);
f(numsToPad[1][0],numsToPad[1][1]);
f(numsToPad[2][0],numsToPad[2][1]);
f(numsToPad[3][0],numsToPad[3][1]);
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. Here’s a list of current revisions for this page:

0 comments

Add a comment