DEV Community

Cover image for How to Add Leading Zero to Number in JavaScript (Bite-size article)
koshirok096
koshirok096

Posted on

How to Add Leading Zero to Number in JavaScript (Bite-size article)

Introduction

Hello everyone.

Have you ever wanted to add a leading zero to numbers in web development or styling, making them "01, 02, 03, ..." instead of just "1, 2, 3, ..."?

Recently, there was a need for such formatting in a project I was working on. It's a very simple issue, but since I hadn't done it personally before, I had to research and solve it on my own. I thought it might be a small learning opportunity, so I decided to share the method I learned in this article. It's a straightforward approach, so some of you might already be familiar with it, but if you're interested, please give it a read.

*I use Javascript for this formatting

Image description

Adding Zeros to One-digit Numbers

In JavaScript, you can add zeros to numbers using the padStart method.

First, look at the sample code below.

function formatSingleDigit(number) {
  return number.toString().padStart(2, '0');
}

console.log(formatSingleDigit(3)); // Output: '03'
Enter fullscreen mode Exit fullscreen mode

Here is basic syntax:

padStart(targetLength)
padStart(targetLength, padString)
Enter fullscreen mode Exit fullscreen mode

targetLength, is the length of the resulting string once the current str has been padded. If the value is shorter than or equal to str.length, then str is returned as-is.

padString is the string to pad the current str (this is optional value). If padString is too long to stay within the targetLength, it will be truncated from the end.


So, the first argument becomes the length of string after padded, and the second argument becomes the character used for pad (in this case, 0).

When using this code, only single-digit numbers will have a leading 0 embedded. The number in formatSingleDigit(number) can be a dynamic value, and you can leverage this code as a foundational structure for various situations.

Bonus: Other Example

This method can be applied to many different uses.
For example, the following uses may be useful.

const serialNumber = 98765;
const formattedSerialNumber = String(serialNumber).padStart(10, '0');
console.log(formattedSerialNumber);  // Output: '0000098765'
Enter fullscreen mode Exit fullscreen mode

This is an example of its use in situations where a certain number of digits are required, for example in formatted serial numbers.
In this way, the missing digits are complemented with '0' to achieve the specified number of digits.

Image description

Conclusion

The content introduced this time is very simple, but I believe it's practical and you may find many opportunities to use it. Please try it if you are interested in.

Thank you for reading!

Top comments (0)