Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript format number to day with always 3 digits [duplicate]

Possible Duplicate:
How can I create a Zerofilled value using JavaScript?

I have to output a day number that must always have 3 digits. Instead of 3 it must write 003, instead of 12 it must write 012. If it is greater than 100 output it without formatting. I wonder if there's a regex that I could use or some quick in-line script, or I must create a function that should do that and return the result. Thanks!

like image 900
ali Avatar asked May 31 '12 21:05

ali


1 Answers

How about:

 zeroFilled = ('000' + x).substr(-3)

For arbitrary width:

 zeroFilled = (new Array(width).join('0') + x).substr(-width)

As per comments, this seems more accurate:

lpad = function(s, width, char) {
    return (s.length >= width) ? s : (new Array(width).join(char) + s).slice(-width);
}
like image 51
georg Avatar answered Oct 07 '22 19:10

georg