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:
007Time
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:05An order number
padStart() is handy for numbers of fixed length:
const orderId = 42;
console.log('ORD-' + String(orderId).padStart(6, '0'));Output:
ORD-000042Common 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
12345Functions used in this recipe
- String.prototype.padStart — Pads a string on the left to a given length.
- String.prototype.padEnd — Pads a string on the right to the desired length.