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

后端 未结 14 1319
走了就别回头了
走了就别回头了 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:40

    The simplest way I can think of is this:

    ("000" + num).slice(-4)
    

    A padded number is a string.
    When you add a number to a string, it is converted to a string.
    Strings has the method slice, that retuns a fixed length piece of the string.
    If length is negative the returned string is sliced from the end of the string.

    to test:

    var num=12;
    console.log(("000" + num).slice(-4)); // Will show "0012"
    

    Of cause this only works for positive integers of up to 4 digits. A slightly more complex solution, will handle positive integers:

    '0'.repeat( Math.max(4 - num.toString().length, 0)) + num
    

    Create a string by repeat adding zeros, as long as the number of digits (length of string) is less than 4 Add the number, that is then converted to a string also.

提交回复
热议问题