我想把一个数格式化为两位数。这个问题是在传递0-9时引起的,所以我需要将它格式化为00-09。
JavaScript中有数字格式化器吗?
我想把一个数格式化为两位数。这个问题是在传递0-9时引起的,所以我需要将它格式化为00-09。
JavaScript中有数字格式化器吗?
当前回答
这是一个简单的数字填充函数,我经常使用。它允许任意数量的填充。
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
其他回答
你可以:
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
function colorOf(r,g,b){
var f = function (x) {
return (x<16 ? '0' : '') + x.toString(16)
};
return "#" + f(r) + f(g) + f(b);
}
@Lifehack的回答对我很有用;我想我们可以用一行来表示正数
String(input).padStart(2, '0');
你可以使用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”
AS数据类型在Javascript中是动态确定的,它将04视为4 如果值小于10,则使用条件语句,然后在其前面添加0,使其成为字符串 例如,
var x=4;
x = x<10?"0"+x:x
console.log(x); // 04