DEV Community

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

Posted on • Edited on

2

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️
`${number}`.padStart(2,0)
Enter fullscreen mode Exit fullscreen mode

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay