3-digit JavaScript daily number

Possible duplicate:
How to create a Zerofilled value using JavaScript?

I need to print the day number, which should always have 3 digits. Instead of 3 he should write 003 , instead of 12 he should write 012 . If it is greater than 100 , output it without formatting. I wonder if there is a regular expression that I could use, or a quick inline script line, or should I create a function that should do this and return the result. Thank!

+5
source share
6 answers

What about:

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

For an arbitrary width:

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

:

lpad = function(s, width, char) {
    return (s.length >= width) ? s : (new Array(width).join(char) + s).slice(-width);
}
+14

. zeroes.

function lpad(value, padding) {
    var zeroes = new Array(padding+1).join("0");
    return (zeroes + value).slice(-padding);
}

: lpad(12, 3) "012"

+3

, :

function zeroFill(number, width) {
    width -= number.toString().length;
    if(width > 0) {
        return new Array(width + (/\./.test(number) ? 2 : 1)).join('0') + number;
    }
    return number + ""; // always return a string
}

(from ?)

, , .

width , , width - number_of_digits - .
new Array(len + 1).join(str) str len .
, , number_of_digits, number.toString().length

+1

:

while ((val+"").length < 3​) {
    val = "0" + val;
}

DEMO: http://jsfiddle.net/WfXVn/

+1

...

("00" + day).slice(-3)

, .slice() 3 .

+1

:

var pad = function(n, length) {
    var str = "" + n;
    if(str.length < length) str = new Array(length - str.length).join("0") + str;
    return str;
};
+1

All Articles