Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to pad a number with leading zeros

Short answer

Convert the number to a string and pad it on the left with padStart():

console.log(String(7).padStart(3, '0'));

Output:

007

Time

This is how time is assembled in the usual format:

const hours = 9;
const minutes = 5;
 
console.log(String(hours).padStart(2, '0') + ':' + String(minutes).padStart(2, '0'));

Output:

09:05

An order number

padStart() is handy for numbers of fixed length:

const orderId = 42;
 
console.log('ORD-' + String(orderId).padStart(6, '0'));

Output:

ORD-000042

Common mistake

Numbers have no padStart() method, it belongs to strings. And if the number is already longer than the target length, it is not cut:

try {
  (7).padStart(3, '0');
} catch (error) {
  console.log(error.name);
}
 
console.log(String(12345).padStart(3, '0'));

Output:

TypeError
12345

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.