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

JavaScript中有数字格式化器吗?


当前回答

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

function zpad(n, len) {
  return 0..toFixed(len).slice(2,-n.toString().length)+n.toString();
}

其他回答

这里有一个简单的递归解决方案,适用于任何数量的数字。

function numToNDigitStr(num, n)
{
    if(num >=  Math.pow(10, n - 1)) { return num; }
    return "0" + numToNDigitStr(num, n-1);
}
<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>

这是一个非常好的和简短的解决方案:

smartTime(time) {
  return time < 10 ? "0" + time.toString().trim() : time;
}

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

我的例子是这样的

         var n =9;
         var checkval=('00'+n).slice(-2);
         console.log(checkval)

输出是09