# How to output integers with leading zeros in JavaScript

2
Answers

You could extend the `Number`

object:

```
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
```

*Examples:*

```
(9).pad(); //returns "09"
(7).pad(3); //returns "007"
```

Question

Possible Duplicate:

How can I create a Zerofilled value using JavaScript?

I can round to x amount of decimal places with math.round but is there a way to round left of the decimal? for example 5 becomes 05 if I specify 2 places

Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:

```
pad.zeros = new Array(5).join('0');
function pad(num, len) {
var str = String(num),
diff = len - str.length;
if(diff <= 0) return str;
if(diff > pad.zeros.length)
pad.zeros = new Array(diff + 1).join('0');
return pad.zeros.substr(0, diff) + str;
}
```

If the padding count is large and the function is called often enough, it actually outperforms the other methods...

From https://gist.github.com/1180489

```
function pad(a,b){return(1e15+a+"").slice(-b)}
```

With comments:

```
function pad(
a, // the number to convert
b // number of resulting characters
){
return (
1e15 + a + // combine with large number
"" // convert to string
).slice(-b) // cut leading "1"
}
```