# Pad a number with leading zeros in JavaScript

```
function padToFour(number) {
if (number<=9999) { number = ("000"+number).slice(-4); }
return number;
}
```

Something like that?

*Bonus incomprehensible-but-slicker single-line ES6 version:*

```
let padToFour = number => number <= 9999 ? ("000"+number).slice(-4) : number;
```

ES6isms:

`let`

is a block scoped variable (as opposed to`var`

’s functional scoping)`=>`

is an arrow function that among other things replaces`function`

and is prepended by its parameters- If a arrow function takes a single parameter you can omit the parentheses (hence
`number =>`

) - If an arrow function body has a single line that starts with
`return`

you can omit the braces and the`return`

keyword and simply use the expression - To get the function body down to a single line I cheated and used a ternary expression

Possible Duplicate:

How can I create a Zerofilled value using JavaScript?

In JavaScript, I need to have padding.

For example, if I have the number 9, it will be "0009". If I have a number of say 10, it will be "0010". Notice how it will always contain four digits.

One way to do this would be to subtract the number minus 4 to get the number of 0s I need to put.

Is there was a slicker way of doing this?

You could do something like this:

```
function pad ( num, size ) {
return ( Math.pow( 10, size ) + ~~num ).toString().substring( 1 );
}
```

Edit: This was just a basic idea for a function, but to add support for larger numbers (as well as invalid input), this would probably be better:

```
function pad ( num, size ) {
if (num.toString().length >= size) return num;
return ( Math.pow( 10, size ) + Math.floor(num) ).toString().substring( 1 );
}
```

This does 2 things:

- If the number is larger than the specified size, it will simply return the number.
- Using
`Math.floor(num)`

in place of`~~num`

will support larger numbers.

For fun, instead of using a loop to create the extra zeros:

```
function zeroPad(n,length){
var s=n+"",needed=length-s.length;
if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
return s;
}
```

Funny, I recently had to do this.

```
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
```

Use like:

```
padDigits(9, 4); // "0009"
padDigits(10, 4); // "0010"
padDigits(15000, 4); // "15000"
```

Not beautiful, but effective.