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").
Here's what I used to pad a number up to 7 characters.
This approach will probably suffice for most people.
Edit: If you want to make it more generic you can do this:
Here's a quick function I came up with to do the job. If anyone has a simpler approach, feel free to share!
In a proposed (stage 3) ES2017 method
.padStart()
you can simply now do (when implemented/supported):Not that this question needs more answers, but I thought I would add the simple lodash version of this.
_.padLeft(number, 6, '0')
Simple way. You could add string multiplication for the pad and turn it into a function.
As a function,
The quick and dirty way:
For x = 5 and count = 6 you'll have y = "000005"