8

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
David
  • 101
  • 1
  • 1
  • 5
  • More duplicates: http://stackoverflow.com/questions/10073699/pad-a-number-with-leading-zeros-in-javascript?lq=1, http://stackoverflow.com/questions/10841773/javascript-format-number-to-day-with-always-3-digits?lq=1, http://stackoverflow.com/questions/16868353/how-to-zero-pad-numbers-in-javascript?lq=1, http://stackoverflow.com/questions/18828797/form-field-input-number-automatically-convert-to-3-digit-by-adding-zeros-in-fro?lq=1 – Felix Kling Aug 08 '14 at 08:32

3 Answers3

18

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

Rahul Tripathi
  • 152,732
  • 28
  • 233
  • 299
5

Just try with:

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

var output = zeroPad(123, 10);

Output:

"0000000123"
hsz
  • 136,835
  • 55
  • 236
  • 297
-2

Another variant would be:

function pad(input, length) {
    return Array(length - Math.floor(Math.log10(input))).join('0') + input;
}

var out = pad(23, 4); // is "0023"
Ferdi265
  • 2,179
  • 15
  • 15