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").
ECMAScript 2017: use padStart or padEnd
More info:
Unfortunately, there are a lot of needless complicated suggestions for this problem, typically involving writing your own function to do math or string manipulation or calling a third-party utility. However, there is a standard way of doing this in the base JavaScript library with just one line of code. It might be worth wrapping this one line of code in a function to avoid having to specify parameters that you never want to change like the local name or style.
This will produce the value of "005" for text. You can also use the toLocaleString function of Number to pad zeros to the right side of the decimal point.
This will produce the value of "5.00" for text. Change useGrouping to true to use comma separators for thousands.
Note that using
toLocaleString()
withlocales
andoptions
arguments is standardized separately in ECMA-402, not in ECMAScript. As of today, some browsers only implement basic support, i.e.toLocaleString()
may ignore any arguments.Complete Example
I can't believe all the complex answers on here... Just use this:
In all modern browsers you can use
Here is the MDN reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
Why not use recursion?
The simplest, most straight-forward solution you will find.