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

JavaScript中有数字格式化器吗?


当前回答

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

其他回答

使用这个函数,你可以打印任意n个数字

function frmtDigit(num, n) {
    isMinus = num < 0;
    if (isMinus)
        num *= -1;
    digit = '';
    if (typeof n == 'undefined')
        n = 2;//two digits
    for (i = 1; i < n; i++) {
        if (num < (1 + Array(i + 1).join("0")))
            digit += '0';
    }
    digit = (isMinus ? '-' : '') + digit + num;
    return digit;
};

在任意数字中使用toLocaleString()方法。因此,对于数字6,如下所示,您可以得到所需的结果。

(6).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})

将生成字符串'06'。

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

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

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(填充数字); } );

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