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

JavaScript中有数字格式化器吗?


当前回答

我知道这是一个古老的帖子,但我想提供一个更灵活和面向对象的解决方案选项。

我已经推断了接受的答案,并扩展了javascript的Number对象,以允许可调的零填充:

Number.prototype.zeroPad =函数(数字){ Var循环=数字; Var 0 = ""; While(循环){ 零+= "0"; 循环,; } 返回(this.toString()。长度为>位数)? this. tostring ():(0 + this).slice(-digits); } Var v = 5; console.log (v.zeroPad (2));//返回"05" console.log (v.zeroPad (4));//返回"0005"

编辑:添加代码以防止截断比要求的数字更长的数字。

注意:除了IE,这在其他所有浏览器中都是过时的。请改用padStart()。

其他回答

你可以:

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/

之前答案的改进版本

函数atLeast2Digit (n) { n = parseInt(n);/ /交货。如果已经经过'05',它将被转换为数字5 Var ret = n > 9 ?" + n: "0" + n; 返回受潮湿腐烂; } alert (atLeast2Digit (5));

我的版本:

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

这是我发现的最简单的解决方法:-

let num = 9; // any number between 0 & 99
let result = ( '0' + num ).substr( -2 );