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

JavaScript中有数字格式化器吗?


当前回答

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

其他回答

你可以:

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

如果数字大于9,则将数字转换为字符串(一致性)。否则,加一个零。

function n(n){
    return n > 9 ? "" + n: "0" + n;
}

n( 9); //Returns "09"
n(10); //Returns "10"
n(999);//Returns "999"

快速和肮脏的一个班轮....

function zpad(n, len) {
  return 0..toFixed(len).slice(2,-n.toString().length)+n.toString();
}
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $('#test').keypress(allowOnlyTwoPositiveDigts);
            });

            function allowOnlyTwoPositiveDigts(e){

                var test = /^[\-]?[0-9]{1,2}?$/
                return test.test(this.value+String.fromCharCode(e.which))
            }

        </script>
    </head>
    <body>
        <input id="test" type="text" />
    </body>
</html>

对于任何想要有时间差并得到负数结果的人来说,这是一个很好的例子。垫(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);
  }
}