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

删除回忆录丶 提交于 2019-11-28 00:02:29

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);
}

I found an elegant solution by Samuel Mullen on his blog. I simply optimized the zeroes creation.

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

Usage: lpad(12, 3) results in "012"

You can do this...

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

It'll prepend the zeros, and then .slice() will always give you the last 3 values of the string.

ThiefMaster

Here is a simple function that pads a number with zeroes to a certain width:

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 How can I pad a value with leading zeros?)

Since the original answer did not explain how the function works I'll do it here.

width initially contains the total length you want, so width - number_of_digits is the number of padding chars necessary.
new Array(len + 1).join(str) repeats str len times.
The regex is used to add an additional padding zero in case of a number containing a decimal point since the point was also included in the number_of_digits determined using number.toString().length

One possible solution:

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

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

I would write the following function:

var pad = function(n, length) {
    var str = "" + n;
    if(str.length < length) str = new Array(length - str.length).join("0") + str;
    return str;
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!