After a, long, long time of testing 15 different functions/methods found in this questions answers, I now know which is the best (the most versatile and quickest).
I took 15 functions/methods from the answers to this question and made a script to measure the time taken to execute 100 pads. Each pad would pad the number 9 with 2000 zeros. This may seem excessive, and it is, but it gives you a good idea about the scaling of the functions.
The code I used can be found here: https://gist.github.com/NextToNothing/6325915
Feel free to modify and test the code yourself.
In order to get the most versatile method, you have to use a loop. This is because with very large numbers others are likely to fail, whereas, this will succeed.
So, which loop to use? Well, that would be a while loop. A for loop is still fast, but a while loop is just slightly quicker(a couple of ms) - and cleaner.
Answers like those by Wilco, Aleksandar Toplek or Vitim.us will do the job perfectly.
Personally, I tried a different approach. I tried to use a recursive function to pad the string/number. It worked out better than methods joining an array but, still, didn't work as quick as a for loop.
My function is:
function pad(str, max, padder) { padder = typeof padder === "undefined" ? "0" : padder; return str.toString().length < max ? pad(padder.toString() + str, max, padder) : str; }
You can use my function with, or without, setting the padding variable. So like this:
pad(1, 3); // Returns '001' // - Or - pad(1, 3, "x"); // Returns 'xx1'
Personally, after my tests, I would use a method with a while loop, like Aleksandar Toplek or Vitim.us. However, I would modify it slightly so that you are able to set the padding string.
So, I would use this code:
function padLeft(str, len, pad) { pad = typeof pad === "undefined" ? "0" : pad + ""; str = str + ""; while(str.length < len) { str = pad + str; } return str; } // Usage padLeft(1, 3); // Returns '001' // - Or - padLeft(1, 3, "x"); // Returns 'xx1'
You could also use it as a prototype function, by using this code:
Number.prototype.padLeft = function(len, pad) { pad = typeof pad === "undefined" ? "0" : pad + ""; var str = this + ""; while(str.length < len) { str = pad + str; } return str; } // Usage var num = 1; num.padLeft(3); // Returns '001' // - Or - num.padLeft(3, "x"); // Returns 'xx1'
npm install sprintf-js, and require it in the file you need:sprintf('%0d6', 5);function padWithZeroes(n, width) { while(n.length<width) n = '0' + n; return n;}...assumingnnot negativewhilein order to accessn.lengthmynum = "0".repeat((n=6-mynum.toString().length)>0?n:0)+mynum;