Simplest way to add a leading zero to a number in Javascript

Hardique Dasore
1 min readAug 27, 2021

--

The simplest way to pad a number with leading zero is to use padStart() method provides by Javascript. We can use this for numbers less than 10.

Syntax

string.padStart(targetLength, padString)

Parameters

targetLength: length of the final string

padstring: string you want to pad/add to given number.

Example

const number = 9;console.log(number.toString().padStart(2, '0'))//Output: 09

Alternatively use can also use:

  1. slice() method

In this method, we add a zero to the number and slice to extract 2 digit value of the result. We use negative value to select from end of the string.

const number = 9;console.log(("0" + number).slice(-2))//Output: 09

2. if check for numbers less than 10

const number = 9;if(number< 10){
console.log("0" + number);
}
else{
console.log(number)
}
//Output: 09

Use case: When you want to display timer in your web application. You need to pad leading zero to minutes and seconds less than 10.

--

--

Hardique Dasore

Hardique is a dynamic Frontend/UI Developer with 4 years of experience creating streamlined and and intuitive controls through programming.