How to add leading zero to a number in JavaScript

By

Learn how to add a leading zero to a number in JavaScript using padStart, so values under 10 print as 09 instead of 9, handy for clock-style displays.

~~~

To add a leading zero to a number in JavaScript, convert it to a string and call padStart(2, '0') on it. A number below 10 comes out with a zero in front, a number with two or more digits stays untouched.

I had the need for this when the number I had was less than 10, so instead of printing “9” on the screen, I wanted “09”.

The use case being I wanted to display the length of a video, and 5:04 is more logical than 5:4 to say a video is 5 minutes and 4 seconds.

Here’s how I did it:

Math.floor(mynumber)
  .toString()
  .padStart(2, '0')

All of this is native to JavaScript, using the Math built-in library.

How does padStart work?

padStart() is a string method. It takes the target length and the string to pad with, and it adds the padding at the start until the string reaches that length:

String(9).padStart(2, '0') // '09'

If the string is already at the target length or longer, nothing changes:

String(12).padStart(2, '0') // '12'
String(125).padStart(2, '0') // '125'

That last behavior matters: padStart() never truncates. It only adds.

The Math.floor() call in my snippet drops any decimal part first, so 9.7 seconds becomes 9, then '09'.

The full video duration example

Here’s the complete version, starting from a duration in seconds:

const duration = 304 //seconds

const minutes = Math.floor(duration / 60)
const seconds = duration % 60

const time = `${minutes}:${seconds.toString().padStart(2, '0')}`
// '5:04'

I only pad the seconds. Padding the minutes too would give 05:04, which is what you want for a clock display, but not for a video length.

A common mistake

padStart() exists on strings, not on numbers. If you call it on a number directly, you get an error:

(9).padStart(2, '0')
// TypeError: 9.padStart is not a function

That’s why the conversion step comes first, either with .toString() or with String(). Both work the same here, pick the one you find more readable.

~~~

Related posts about js: