开发者

Working with number in JavaScript

开发者 https://www.devze.com 2023-02-18 00:49 出处:网络
How could I d开发者_开发知识库o this? 1 -> 01 4 -> 04 9 -> 09 11 -> 11 22 -> 22 Thanks!Almost a duplicate of 610406. The simple thing, if you only want to add a 0 to numbers less tha

How could I d开发者_开发知识库o this?

1 -> 01
4 -> 04
9 -> 09
11 -> 11
22 -> 22

Thanks!


Almost a duplicate of 610406. The simple thing, if you only want to add a 0 to numbers less than 10 would be something like:

function formatNum(num) {
    if (num < 10) {
        return '0' + num;
    }

    return num + '';
}


var result = myNumber.toString(10);
if(myint < 10)
{
  result = "0" + result;
}


var i = 9;
i = "0" + i;
i = i.substring(i.length - 2);


If you want something flexible:

Number.prototype.pad = function(length){
    return (new Array(length - this.toString().length + 1)).join('0') + this;
}

var x = 6;
x.pad(2); // 06

or if you want the basic 2-digit only:

x<10 ? '0'+x : x
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号