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

本小妞迷上赌 提交于 2019-11-26 23:21:45

问题


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!


回答1:


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



回答2:


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"




回答3:


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.




回答4:


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




回答5:


One possible solution:

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

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




回答6:


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


来源:https://stackoverflow.com/questions/10841773/javascript-format-number-to-day-with-always-3-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!