What is the recommended way to zerofill a value in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?
Note: By "zerofilled" I mean it in the database sense of the word (where a 6-digit zerofilled representation of the number 5 would be "000005").
My solution
Usage
If the fill number is known in advance not to exceed a certain value, there's another way to do this with no loops:
Test cases here: http://jsfiddle.net/jfriend00/N87mZ/
This is the ES6 solution.
Some monkeypatching also works
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
with2000
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. Afor
loop is still fast, but awhile
loop is just slightly quicker(a couple of ms) - and cleaner.Answers like those by
Wilco
,Aleksandar Toplek
orVitim.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:
You can use my function with, or without, setting the padding variable. So like this:
Personally, after my tests, I would use a method with a while loop, like
Aleksandar Toplek
orVitim.us
. However, I would modify it slightly so that you are able to set the padding string.So, I would use this code:
You could also use it as a prototype function, by using this code:
Just an another solution, but I think it's more legible.