Left zero pad (v6)

Revision 6 of this benchmark created on


Description

Belonging to this question on StackOverflow.

Setup

var numsToPad = [
      [1, 100],
      [-123, 4],
      [5.619, 7],
      [1234567890, 2]
    ];

Test runner

Ready to run.

Testing in
TestOps/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]);
ready
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]);
ready
coderjoe's
function f(n, w) {
  if (n.toString().length >= w) return n.toString();
  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]);
ready

Revisions

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