Pad left for numbers (v4)

Revision 4 of this benchmark created on


Preparation HTML

<script>
  // http://twitter.com/cowboy/status/15344233981
  
  function pad(n, d) {
   return Array(Math.max(0, d - (n + '').length + 1)).join(0) + n;
  };
  
  // http://www.electrictoolbox.com/pad-number-zeroes-javascript/
  
  function pad2(number, length) {
   var str = '' + number;
   while (str.length < length) {
    str = '0' + str;
   };
   return str;
  };
  
  function pad3(n, d) {
   return ((Math.pow(10, d) + n) + '').substr(1);
  };
  
  function pad4(n, d) {
   return ('00000000000000' + n).slice(-d);
  }
  
  // pad2 with cached padLength
  
  function pad5(n, d) {
   var padLength = d - ('' + n).length;
   if (padLength > 0) {
    while (padLength--) {
     n = '0' + n;
    }
   }
   return n;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Ben Alman’s pad() function
pad(1, 5); // 00001
pad(12, 4); // 0012
pad(123, 2); // 123
ready
The pad2() function
pad2(1, 5); // 00001
pad2(12, 4); // 0012
pad2(123, 2); // 123
ready
The pad3() function
pad3(1, 5); // 00001
pad3(12, 4); // 0012
pad3(123, 2); // 123
ready
The pad4() function
pad4(1, 5); // 00001
pad4(12, 4); // 0012
pad4(123, 2); // 123
ready
The pad5() function
pad5(1, 5); // 00001
pad5(12, 4); // 0012
pad5(123, 2); // 123
ready

Revisions

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