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").
Late to the party here, but I often use this construct for doing ad-hoc padding of some value
n
, known to be a positive, decimal:Where
offset
is 10^^digits.E.g. Padding to 5 digits, where n = 123:
The hexidecimal version of this is slightly more verbose:
Note 1: I like @profitehlolz's solution as well, which is the string version of this, using slice()'s nifty negative-index feature.
Don't reinvent the wheel, use underscore string:
jsFiddle
I actually had to come up with something like this recently. I figured there had to be a way to do it without using loops.
This is what I came up with.
Then just use it providing a number to zero pad:
If the number is larger than the padding, the number will expand beyond the padding:
Decimals are fine too!
If you don't mind polluting the global namespace you can add it to Number directly:
And if you'd rather have decimals take up space in the padding:
Cheers!
XDR came up with a logarithmic variation that seems to perform better.
WARNING: This function fails if num equals zero (e.g. zeropad(0, 2))
Speaking of performance, tomsmeding compared the top 3 answers (4 with the log variation). Guess which one majorly outperformed the other two? :)
This one is less native, but may be the fastest...
I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.
A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:
Generalizing we'll get:
The latest way to do this is much simpler:
output: "02"