Emmanuel Akinfulubi

JavaScriptString

Add leading zeros to a number in JavaScript

Beginner · 3 min read

Clocks show 09:05, not 9:5. Invoices are numbered 000042, not 42. Dates in files are written 2025-04-09. In each case a number is shown with zeros in front so it always takes up the same number of digits. These are called leading zeros.

In this tutorial you will write pad2, a function that turns 7 into '07', use it to build a clock that shows 09:05, and then format an invoice number six digits wide. Along the way you will see why the result must stay a string. You should know what a function is. padStart is explained below.

Numbers can't hold leading zeros

To JavaScript, 007 and 7 are the same number. A number stores a value, not how it is written, so there is nowhere to keep the zeros:

JavaScript

console.log(7 === Number('007')); // true

So leading zeros are a job for text. You turn the number into a string, then add zeros to the front of the string.

padStart in one line

text.padStart(width, filler) adds filler to the left of text until the whole thing is width characters long. So '7'.padStart(2, '0') gives '07'. The width is the final length, not the number of zeros to add.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

20 Zero-pad a number

easy

Format hours and minutes as 09:05. Then format an invoice number six digits wide.

Stuck? Three hints, smallest first
  1. 1. padStart is a string method, so convert the number first.
  2. 2. String(n) or `${n}` both do the conversion.
  3. 3. A number cannot store a leading zero, so the padded form has to stay a string.

Step 1: try padStart on a number

The natural first attempt is to call padStart on the number directly:

JavaScript

const n = 7;
console.log(n.padStart(2, '0')); // TypeError: n.padStart is not a function

padStart belongs to strings, and n is a number. Numbers don't have it.

Step 2: convert first, then pad

String(n) turns the number into text. Now padStart works.

Step 2

const pad2 = (n) => String(n).padStart(2, '0');
console.log(pad2(7));  // '07'
console.log(pad2(23)); // '23'
console.log(pad2(0));  // '00'

Two-digit numbers are already wide enough, so they pass through. Zero becomes '00', which is just what a clock wants at midnight. A template literal, `${n}`, converts a number to text too, and you can use whichever you prefer.

Step 3: build a clock

A template literal is a string written between backticks. Anything inside ${ } is worked out and dropped into the text.

Step 3

const pad2 = (n) => String(n).padStart(2, '0');
const clock = (h, m) => `${pad2(h)}:${pad2(m)}`;
console.log(clock(9, 5)); // '09:05'
console.log(clock(0, 0)); // '00:00'

Each part is padded on its own, then joined with a colon.

Step 4: a number that is too wide

What if the number already has more digits than the width?

Step 4

const pad2 = (n) => String(n).padStart(2, '0');
console.log(pad2(123));                     // '123'
console.log(String(123).padStart(4, '0'));  // '0123'

padStart never removes characters, so 123 comes back whole. That is safer than cutting it, because a wrong number is worse than a wide one. If your values can be bigger, choose a wider field, as the second line does.

Step 5: an invoice number, six digits wide

The same tool works for any width.

Step 5

const invoice = String(42).padStart(6, '0');
console.log(invoice);        // '000042'
console.log(typeof invoice); // 'string'

'42' is 2 characters, so four zeros are added to reach 6.

Step 6: keep it a string

The padded value is a string, and it must stay one until it reaches the screen.

Step 6

const pad2 = (n) => String(n).padStart(2, '0');
console.log(typeof pad2(7));  // 'string'
console.log(Number(pad2(7))); // 7

The moment you turn '07' back into a number, the zero is gone. So do your maths with numbers, and pad only at the very end, when you display the result.

The full solution

Here is the complete answer: pad2, the clock, a number too wide for its field, and the invoice number. Press Run to see each result.

The answer

const pad2 = (n) => String(n).padStart(2, '0');
const clock = (h, m) => `${pad2(h)}:${pad2(m)}`;

console.log('clock(9, 5)  :', clock(9, 5));
console.log('clock(0, 0)  :', clock(0, 0));
console.log('pad2(123)    :', pad2(123), '<- wider than the field, so nothing is cut');
console.log('Number("07") :', Number(pad2(7)), '<- the zero is gone the moment it is a number again');

Output


      
10 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('a single digit gains a zero', pad2(7), '07');
test('two digits are left alone', pad2(23), '23');
test('zero becomes 00', pad2(0), '00');
test('a clock reads properly', clock(9, 5), '09:05');
test('and at midnight', clock(0, 0), '00:00');
test('padStart is a string method, so the result is a string', typeof pad2(7), 'string');
test('converting back loses the padding, because numbers have no leading zeros', Number(pad2(7)), 7);
test('three digits overflow the field rather than being cut', pad2(123), '123');
test('so widen the field when the range is bigger', String(123).padStart(4, '0'), '0123');
test('an invoice number, six wide', String(42).padStart(6, '0'), '000042');

The padded value has to remain a string all the way to the screen. The moment it becomes a number again the zeros are gone, because 007 and 7 are the same number — that is what the Number(pad2(7)) assertion is there to show.

Beware of parseInt on a zero-padded string in very old code: it used to read a leading zero as octal, so '08' became 0. Modern engines do not, but the habit of passing the radix — parseInt('08', 10) — survives from that era and is still worth keeping.

Common mistakes

  • Calling padStart on a number. It throws TypeError: n.padStart is not a function. Use String(n) first.
  • Using the padded value in maths. '07' + 1 is '071', because + joins text. Keep the number for sums and pad for display.
  • Getting the width wrong. The first argument is the total width. padStart(6, '0') gives six characters, not six zeros.

Try it yourself

  1. Write formatDate(y, m, d) that returns '2025-04-09' for formatDate(2025, 4, 9).
  2. Write timer(seconds) that turns 125 into '02:05'. (Hint: Math.floor(seconds / 60) and seconds % 60.)
  3. Format a list of ticket numbers [1, 42, 300] as ['T-0001', 'T-0042', 'T-0300'].

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.