How can I pad a value with leading zeros?

Wilco picture Wilco · Aug 12, 2009 · Viewed 229.2k times · Source

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").

Answer

Seaux picture Seaux · Dec 9, 2013

I can't believe all the complex answers on here... Just use this:

var zerofilled = ('0000'+n).slice(-4);