How to Pad a number with Leading Zeros in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 23, 2021

banner

Check out my new book

Pad a number with Leading Zeros #

To pad a number with leading zeros convert the number to a string and call the padStart() method. The padStart method allows you to add leading zeros to the start of the string until it reaches the specified target length.

index.js
function padWithZero(num, targetLength) { return String(num).padStart(targetLength, '0') } console.log(padWithZero(5, 2)); // 👉️ '05' console.log(padWithZero(5, 3)); // 👉️ '005' console.log(padWithZero(5, 4)); // 👉️ '0005'

We created a reusable function that pads a number with leading zeros.

The padStart method has to be used on a string, so the first step is to convert the number.

We passed the following 2 parameters to the padStart method:

  1. target length - the length of the string the padStart method should return, once it has been padded.
  2. pad string - the string we want to pad our existing string with.

If you have a string of length 2 and specify a targetLength of 4, then 2 leading zeros will be added to the string.

index.js
console.log(String(22).padStart(4, '0')); // 👉️ '0022'

Note that the padStart method returns a string. If you were to convert the result back to a number, the leading zeros would get dropped.

index.js
function padWithZero(num, targetLength) { return String(num).padStart(targetLength, '0') } console.log(Number(padWithZero(5, 10))); // 👉️ 5

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.