How to Pad a number with Leading Zeros in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 23 20211 min read

banner

Photo by Samuel Austin

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee