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

JavaScript中有数字格式化器吗?


当前回答

这是一个非常好的和简短的解决方案:

smartTime(time) {
  return time < 10 ? "0" + time.toString().trim() : time;
}

其他回答

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

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

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

如果您的项目中没有lodash,那么仅仅为了使用一个函数而添加整个库将是一种过度。这是我见过的最复杂的解决你问题的方法。

_.padStart(num, 2, '0')

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

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(填充数字); } );

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

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

为ES6箭头函数更新(几乎所有现代浏览器都支持,参见CanIUse)

const formatNumber = n => ("0" + n).slice(-2);