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

后端 未结 14 1271
走了就别回头了
走了就别回头了 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).

    0 讨论(0)
  • 2021-02-03 18:00

    I think the most compact yet intuitive way is:

    function toFixedLength(input, length, padding) {
        padding = String(padding || "0");
        return (padding.repeat(length) + input).slice(-length);
    }
    

    The slice method here could be replaced with substr if that is more intuitive to the coder.

    0 讨论(0)
提交回复
热议问题