Format a Number, Exactly Two in Length?

前端 未结 10 644
既然无缘
既然无缘 2021-02-03 21:49

I have an integer that is less then 100 and is printed to an HTML page with JavaScript. How do I format the integer so that it is exactly two digits long? For example:

10条回答
  •  执笔经年
    2021-02-03 22:09

    function padLeft(a, b) {
        var l = (a + '').length;
        if (l >= b) {
            return a + '';
        } else {
            var arr = [];
            for (var i = 0; i < b - l ;i++) {
                arr.push('0');
            }
            arr.push(a);
            return arr.join('');
        }
    }
    

提交回复
热议问题