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

JavaScript中有数字格式化器吗?


当前回答

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

其他回答

“${}数量”.replace (/ ^ (\ d) /美元,' 0 $ 1 ');

正则表达式是最好的。

这是一个简单的数字填充函数,我经常使用。它允许任意数量的填充。

function leftPad(number, targetLength) {
    var output = number + '';
    while (output.length < targetLength) {
        output = '0' + output;
    }
    return output;
}

例子:

leftPad(1, 2) // 01
leftPad(10, 2) // 10
leftPad(100, 2) // 100
leftPad(1, 3) // 001
leftPad(1, 8) // 00000001

在所有现代浏览器中都可以使用

numberStr.padStart(2, "0");

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

函数 zeroPad(numberStr) { 返回 numberStr.padStart(2, “0”); } 变量数 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 数字.forEach( 函数(数字) { var numString = num.toString(); var ppadNum = zeroPad(numString); console.log(填充数字); } );

AS数据类型在Javascript中是动态确定的,它将04视为4 如果值小于10,则使用条件语句,然后在其前面添加0,使其成为字符串 例如,

var x=4;
  x = x<10?"0"+x:x
 console.log(x); // 04

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