Sometime you may want to format integer values nicely to have the same number of digit, for example for element ids, similar to what the auto-counter is doing:
1 -> 001
12 -> 012
123 -> 123
The JS language has no built-in support here but the net offers some nice solutions, the simplest one is to use "slice" like this:
//#1
var num=12;
console.log(("0000" + num).slice(-4)); // Will show "0012"
Pressing this into a function would make it reusable and avoid a fixed slide parameter:
//#2
function formatInteger(format, value) {
return (format + num).slice(-format.length);
}
console.log(formatInteger("0000", num)); // Will show "0012"
We can use the format to even do some more sanity checks like this:
//#3
function formatInteger2(format, value) {
var limit = Math.pow(10, format.length-1);
if (num >= limit) {
throw "The number " + value + " is byond the limit " + limit;
}
console.log(limit);
return (format + num).slice(-format.length);
}
console.log(formatInteger2("0000", num)); // Will show "0012"
console.log(formatInteger2("00", 123)); // This will fail
Happy Scripting
Jan