0
0
JavascriptHow-ToBeginner · 3 min read

How to Pad Number with Leading Zeros in JavaScript

To pad a number with leading zeros in JavaScript, convert the number to a string and use the padStart method with the desired total length and '0' as the padding character. For example, num.toString().padStart(5, '0') will add zeros to the left until the string length is 5.
📐

Syntax

The main method to pad numbers with leading zeros is padStart. It is called on a string and takes two arguments:

  • targetLength: The total length of the resulting string after padding.
  • padString: The string to pad with, usually '0' for leading zeros.

Since numbers are not strings, you first convert the number to a string using toString().

javascript
number.toString().padStart(targetLength, '0')
💻

Example

This example shows how to pad the number 42 with leading zeros to make it 5 characters long.

javascript
const num = 42;
const padded = num.toString().padStart(5, '0');
console.log(padded);
Output
00042
⚠️

Common Pitfalls

One common mistake is trying to pad the number directly without converting it to a string, which causes an error because numbers don't have padStart. Another is using string concatenation manually, which can be error-prone and less readable.

javascript
const num = 7;
// Wrong: numbers don't have padStart
// const paddedWrong = num.padStart(3, '0'); // Error

// Right way:
const paddedRight = num.toString().padStart(3, '0');
console.log(paddedRight);
Output
007
📊

Quick Reference

Use toString() to convert numbers to strings, then padStart to add leading zeros.

  • padStart(totalLength, '0'): Pads string on the left with zeros until it reaches totalLength.
  • Works well for formatting numbers like IDs, codes, or time values.

Key Takeaways

Convert numbers to strings before padding with leading zeros using toString().
Use padStart(targetLength, '0') to add leading zeros easily and clearly.
Avoid trying to call padStart directly on numbers as it causes errors.
Leading zero padding is useful for formatting numbers to fixed width strings.