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").
I really don't know why, but no one did it in the most obvious way. Here it's my implementation.
Function:
Prototype:
Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.
First parameter is any real number, second parameter is a positive integer specifying the minimum number of digits to the left of the decimal point and third parameter is an optional positive integer specifying the number if digits to the right of the decimal point.
so
The power of Math!
x = integer to pad
y = number of zeroes to pad
pad(5, 0, 6)
=000005
pad('10', 0, 2)
=10 // don't pad if not necessary
pad('S', 'O', 2)
=SO
...etc.
Cheers
A simple function is all you need
you could bake this into a library if you want to conserve namespace or whatever. Like with jQuery's extend.
I use this snipet to get a 5 digits representation