Adding leading zeros in JavaScript

Leading zeros are simply one or more zeros before an integer – but you probably already knew that.

Sometimes when you’re writing code, you’ll want to add a specific number of leading zeros to a number.

For example, if you’ve got a month of the year and you need to use the dd/mm/yyyy format, you will need to add a leading zero to January (1 to 01) through to September (9 to 09).

// A number to add leading zeros too
let yourNumber = 9

// Round the number to the nearest integer
yourNumber = Math.round(yourNumber)

// Convert the number to a string
yourNumber = yourNumber.toString()

// Add zeros to the beginning of the number until it is two numbers long
yourNumber = yourNumber.padStart(2, "0")

// Result: 09

Alter the first number in padStart to add different numbers of leading zeros.

Bear in mind it’s not really a number because integers do not start with zeros.

That’s it – told you it was a quick and easy one.

Share