DEV Community

Cover image for Simplest way to add a leading zero to a number in Javascript
Hardique Dasore
Hardique Dasore

Posted on • Updated on

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

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

2. if check for numbers less than 10

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

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.

Image description

Follow us on Instagram

Oldest comments (1)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ
`${number}`.padStart(2,0)
Enter fullscreen mode Exit fullscreen mode