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

JavaScript中有数字格式化器吗?


当前回答

    function colorOf(r,g,b){
  var f = function (x) {
    return (x<16 ? '0' : '') + x.toString(16) 
  };

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

其他回答

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

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

@Lifehack的回答对我很有用;我想我们可以用一行来表示正数

 String(input).padStart(2, '0');

我的版本:

`${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)));

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

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