How can I format an integer to a specific length in javascript?

后端 未结 14 1305
走了就别回头了
走了就别回头了 2021-02-03 17:06

I have a number in Javascript, that I know is less than 10000 and also non-negative. I want to display it as a four-digit number, with leading zeroes. Is there anything more e

14条回答
  •  忘了有多久
    2021-02-03 17:58

    I don't think there's anything "built" into the JavaScript language for doing this. Here's a simple function that does this:

    function FormatNumberLength(num, length) {
        var r = "" + num;
        while (r.length < length) {
            r = "0" + r;
        }
        return r;
    }
    
    
    FormatNumberLength(10000, 5) outputs '10000'
    FormatNumberLength(1000, 5)  outputs '01000'
    FormatNumberLength(100, 5)   outputs '00100'
    FormatNumberLength(10, 5)    outputs '00010'
    

提交回复
热议问题