我想把一个数格式化为两位数。这个问题是在传递0-9时引起的,所以我需要将它格式化为00-09。
JavaScript中有数字格式化器吗?
我想把一个数格式化为两位数。这个问题是在传递0-9时引起的,所以我需要将它格式化为00-09。
JavaScript中有数字格式化器吗?
当前回答
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);
}
其他回答
你可以:
function pad2(number) {
return (number < 10 ? '0' : '') + number
}
例子:
document.write(pad2(0) + '<br />');
document.write(pad2(1) + '<br />');
document.write(pad2(2) + '<br />');
document.write(pad2(10) + '<br />');
document.write(pad2(15) + '<br />');
结果:
00
01
02
10
15
@Lifehack的回答对我很有用;我想我们可以用一行来表示正数
String(input).padStart(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(填充数字); } );
我的版本:
`${Math.trunc(num / 10)}${Math.trunc(num % 10)}`;
const func = (num) => '${Math.trunc(num / 10)}${Math.trunc(num % 10)}'; 常量数 = [1, 3, 5, 6, 8, 9, 10, 20, 56, 80]; nums.forEach(num => console.log(func(num)));
为ES6箭头函数更新(几乎所有现代浏览器都支持,参见CanIUse)
const formatNumber = n => ("0" + n).slice(-2);