Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding zero to the left of number in Javascript [duplicate]

Tags:

javascript

I have a ten digit number that will always be constant. I want to pad it so, that it will always remove a zero for every extra number added to the number. Can someone please show me an example of how I can do this?

eg. 0000000001

0000000123 
0000011299
like image 951
David Avatar asked Aug 08 '14 08:08

David


2 Answers

You can use this function:

function pad (str, max) {
  str = str.toString();
  return str.length < max ? pad("0" + str, max) : str;
}

Output

pad("123", 10);    // => "0000000123"

JSFIDDLE DEMO

like image 59
Rahul Tripathi Avatar answered Nov 10 '22 01:11

Rahul Tripathi


Just try with:

function zeroPad(input, length) {
    return (Array(length + 1).join('0') + input).slice(-length);
}

var output = zeroPad(123, 10);

Output:

"0000000123"
like image 37
hsz Avatar answered Nov 10 '22 01:11

hsz