我想把一个数格式化为两位数。这个问题是在传递0-9时引起的,所以我需要将它格式化为00-09。

JavaScript中有数字格式化器吗?


当前回答

你可以使用padStart方法:

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

check this example:

函数n(num, len = 2) { 返回“$ {num}”。padStart (len, ' 0 '); } console.log (n (9));/ /打印“09” console.log (n (10));/ /打印“10” console.log (n (999));/ /打印“999” console.log (n(999 6)); / /打印“000999”

其他回答

你可以使用padStart方法:

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

check this example:

函数n(num, len = 2) { 返回“$ {num}”。padStart (len, ' 0 '); } console.log (n (9));/ /打印“09” console.log (n (10));/ /打印“10” console.log (n (999));/ /打印“999” console.log (n(999 6)); / /打印“000999”

在所有现代浏览器中都可以使用

numberStr.padStart(2, "0");

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

函数 zeroPad(numberStr) { 返回 numberStr.padStart(2, “0”); } 变量数 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 数字.forEach( 函数(数字) { var numString = num.toString(); var ppadNum = zeroPad(numString); console.log(填充数字); } );

("0" + (date.getMonth() + 1)).slice(-2);
("0" + (date.getDay())).slice(-2);

JavaScript没有内置的数字格式化器,但是有一些库可以实现这个功能:

下划线。String提供了sprintf函数(以及许多其他有用的格式化方法) Javascript-sprintf,其中下划线。字符串借用。

or

function zpad(n,l){
   return rep(l-n.toString().length, '0') + n.toString();
}

with

function rep(len, chr) { 
   return new Array(len+1).join(chr);
}