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
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).
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.