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

JavaScript中有数字格式化器吗?


当前回答

对于任何想要有时间差并得到负数结果的人来说,这是一个很好的例子。垫(3)=“03”,垫(2)= " -02 ",垫(-234)= " -234 "

pad = function(n){
  if(n >= 0){
    return n > 9 ? "" + n : "0" + n;
  }else{
    return n < -9 ? "" + n : "-0" + Math.abs(n);
  }
}

其他回答

你可以:

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

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

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')
    function colorOf(r,g,b){
  var f = function (x) {
    return (x<16 ? '0' : '') + x.toString(16) 
  };

  return "#" +  f(r) + f(g) + f(b);
}

AS数据类型在Javascript中是动态确定的,它将04视为4 如果值小于10,则使用条件语句,然后在其前面添加0,使其成为字符串 例如,

var x=4;
  x = x<10?"0"+x:x
 console.log(x); // 04