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

后端 未结 14 1284
走了就别回头了
走了就别回头了 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-03 17:52

    A "while" loop should make this easy enough.

    function formatLength(a) {
        var num = document.getElementById(a)
        while (num.value.length < 4) {
            num.value = '0' + num.value
        }
    }
    

    That would loop through until the length of the num value reached 4 digits (assuming you have passed in the id of the number element as an argument)

提交回复
热议问题