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.
Follow us on Instagram
Top comments (1)