Pad left for numbers

Benchmark created by Mathias Bynens 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;
  };
</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

Revisions

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