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

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.

Edit: from now on you should probably use this function:

String(num).padStart(4,'0')

It still doesn’t handle negative numbers…

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)