Skip to content

How to add leading zero to a number in JavaScript

The Valley of Code

Your Web Development Manual

I had the need to add a leading zero when the number I had was less than 10, so instead of printing β€œ9” on the screen, I had β€œ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

β†’ Get my JavaScript Beginner's Handbook
β†’ Read my JavaScript Tutorials on The Valley of Code
β†’ Read my TypeScript Tutorial on The Valley of Code
  • THE VALLEY OF CODE (+ PRO), your web development manual
  • I wrote 15+ free coding BOOKS, download them here
  • SOLOPRENEUR LAND the missing MBA for wannabe solopreneurs craving a life with more freedom, control, fulfillment and purpose (summer 2024)