Ways to 0-pad a number

JavaScript performance comparison

Test case created by Michael A. Smith

Info

There are lots of ways to zero-pad a number in JavaScript. Which is fastest?

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    /**
     * Pad a number with leading zeros to "pad" places:
     *
     * @param number: The number to pad
     * @param pad: The maximum number of leading zeros
     */

    function padNumberMath(number, pad) {
        var N = Math.pow(10, pad);
        return number < N ? ("" + (N + number)).slice(1) : "" + number
    }
    function padNumberArray(n, len) {
      return (new Array(len + 1).join('0') + n).slice(-len);
    }
    function padNumberLoop(number, length) {
        var my_string = '' + number;
        while (my_string.length < length) {
            my_string = '0' + my_string;
        }
        return my_string;
    }
   
   
   
};
</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
Math
padNumberMath(1301, 4);
padNumberMath(120, 4);
padNumberMath(14, 4);
padNumberMath(9, 4);
 
pending…
Array join
padNumberArray(1301, 4);
padNumberArray(120, 4);
padNumberArray(14, 4);
padNumberArray(9, 4);
 
pending…
Loop
padNumberLoop(1301, 4);
padNumberLoop(120, 4);
padNumberLoop(14, 4);
padNumberLoop(9, 4);
 
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:

1 comment

Michael A. Smith commented :

Wow, that's crazy. IE in 64-bit mode does the loop faster. In 32-bit mode it does the Math faster. What gives?

Add a comment