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

JavaScript中有数字格式化器吗?


当前回答

如果您的项目中没有lodash,那么仅仅为了使用一个函数而添加整个库将是一种过度。这是我见过的最复杂的解决你问题的方法。

_.padStart(num, 2, '0')

其他回答

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

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

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

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

function numToNDigitStr(num, n)
{
    if(num >=  Math.pow(10, n - 1)) { return num; }
    return "0" + numToNDigitStr(num, n-1);
}

我的例子是这样的

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

输出是09

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

var num = document.getElementById('input').value,
    replacement = num.replace(/^(\d)$/, '0$1');
document.getElementById('input').value = replacement;

这里有一个例子:http://jsfiddle.net/xtgFp/

<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>