# Zero-padding a number to have six digits

This is a switch statement in JavaScript. I have a feeling that it can be done in a shorter way.

switch(n.length){
case 1:
n = '00000' + n;
break;
case 2:
n = '0000' + n;
break;
case 3:
n = '000' + n;
break;
case 4:
n = '00' + n;
break;
case 5:
n = '0' + n;
break;
}

• I'm curious what this is being used for. It's pretty non-general. Nov 6, 2011 at 20:00
• @HackSaw I believe it's used for left-padding a number. There's a better padding function out there as well: click me Nov 6, 2011 at 23:57

function foobar(n)
{
var zeroes = "000000";
return zeroes.substr(n.length) + n.toString();
}

• ps: there's a small error in the code, it should be: zeroes.substr(n.length) + n.toString();
– Emma
Nov 6, 2011 at 12:42
• Then why you don't use n.length in your code? Nov 6, 2011 at 13:07
• lol sorry, the same mistake is in my code :) anyway thank you, I just needed the idea
– Emma
Nov 6, 2011 at 13:12
• You don’t need the variable. The name zeroes doesn’t add any meaning, so "000000".substr(n.length) is just as clear, and more succinct. Nov 6, 2011 at 22:53

Well, the value of n is known in each case, so you can just put it in the string:

switch(n) {
case 1:
n = '000001';
break;
case 2:
n = '00002';
break;
case 3:
n = '0003';
break;
case 4:
n = '004';
break;
case 5:
n = '05';
break;
}


If n can only have one of these values, you can use it as index in an array:

n = ['000001','00002','0003','004','05'][n - 1];


### Edit:

With the edited code (using n.length in the switch), it would be:

n = ['00000','0000','000','00','0'][n.length - 1] + n;


It seems you're trying to implement part of the functionality of printf. Use one of the existing implementations, e.g. dive.into.javascripts sprintf to do the zero-padding:

n = sprintf("%06d", n);


Currently the other answers do not provide a robust way of doing this. They either use magic numbers or create long strings of zeroes manually. So I am adding this answer as a reference for anyone visiting this question in the future.

We can create the padding by joining an empty array together. I have provided two options: straight code or a function for reuse.

Straight Code:

var desiredLength = 6;

if (n.length < desiredLength) {
n = Array(desiredLength - n.length + 1).join("0") + n;
}


Function:

function padTo(length, str, ch) {
if (str.length < length) {
return Array(length - str.length + 1).join(ch) + str;
}

return str;
}

// Usage