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

JavaScript中有数字格式化器吗?


当前回答

这里有一个简单的递归解决方案,适用于任何数量的数字。

function numToNDigitStr(num, n)
{
    if(num >=  Math.pow(10, n - 1)) { return num; }
    return "0" + numToNDigitStr(num, n-1);
}

其他回答

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

似乎你得到的是一个字符串,而不是一个数字。用这个:

var num = document.getElementById('input').value,
    replacement = num.replace(/^(\d)$/, '0$1');
document.getElementById('input').value = replacement;

这里有一个例子:http://jsfiddle.net/xtgFp/

这是一个简单的数字填充函数,我经常使用。它允许任意数量的填充。

function leftPad(number, targetLength) {
    var output = number + '';
    while (output.length < targetLength) {
        output = '0' + output;
    }
    return output;
}

例子:

leftPad(1, 2) // 01
leftPad(10, 2) // 10
leftPad(100, 2) // 100
leftPad(1, 3) // 001
leftPad(1, 8) // 00000001

“${}数量”.replace (/ ^ (\ d) /美元,' 0 $ 1 ');

正则表达式是最好的。

你可以使用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”