JavaScript to Fill a var with leading zeros.

tmajor99
tmajor99 used Ask the Experts™
on
I need a javascript that will fill a variable with leading zeros so it always stays 7 bytes in length.

For example:
Before                  After
13777                 0013777
  4022                 0004022
1                         0000001
99                       0000099
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
function pad(num, size) {
    var s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}

console.log(pad(1, 7));
console.log(pad(123, 7));
console.log(pad(4567890, 7));

Open in new window

Most Valuable Expert 2013
Awarded 2012
Commented:
Hi,
UPDATE - there was an error in the code - the updated one works:
alternative way
function FillZero(org,size){
  return ('0000000000000'+org).slice(-size);
}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial