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

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

    I ran into much the same problem and I found a compact way to solve it. If I had to use it multiple times in my code or if I was doing it for any more than four digits, I'd use one of the other suggested solutions, but this way lets me put it all in an expression:

    ((x<10)?"000": (x<100)?"00": (x<1000)?"0": "") + x
    

    It's actually the same as your code, but using the ternary operator instead of "if-else" statements (and moving the "+ x", which will always be part of the expression, outside of the conditional code).

提交回复
热议问题