Add leading zero to a number in JavaScript (Code Example)

In this article, we will see how to add a leading zero to a number in Javascript.

Let’s say we have a number 9 which we want to print out in two digits eg 09, then we have to add a zero in front of it.

To achieve that we can use the in-built padStart() method in Javascript.

Add leading zero using padStart() in Javascript

The padStart() method is used to pad a given string with another string until it reaches the given length.

Syntax:

string.padStart(targetLength, padstring)

The targetLength is the length of the final string after padding.

The padstring is the string that we want to pad to the current string.

So to add a leading zero to a number:

  1. First, convert the number to a string using toString().
  2. Call the padStart() method on that string and pass on 2 as the length and ‘0’ as the pad string.

Let’s check the example below to understand it.

Example:

let num  = 9
// convert to string
let num_str = num.toString()

let lead_zero = num_str.padStart(2,'0')

console.log(lead_zero)

Output:

09

Here, we have passed 2 as the length of the string we want and 0 is the string we want to add as the leading value.

Now, it is important to note that the output i.e 09 is a String and not a Number.

And if we try to convert the string value back to number then it will drop the leading 0 from it. It is because 09 is equal to 9 (09 === 9) in Javascript.

Add a leading zero to a negative number in Javascript

If you want to add a leading zero in front of a negative number for example -9 to -09, then we have to use the slice() method, to separate the minus sign and then add it after we have added the zero to the given number.

Example:

let num  = -9

function addLeadingZero(num){

  // convert number to string
  let num_str = num.toString()

  // remove the minus from the string
  remove_minus = num_str.slice(1)

  let lead_zero = remove_minus.padStart(2,'0')

  // add the (-) minus sign back using + operator
  return '-' + lead_zero
}

console.log(addLeadingZero(num))

Output:

-09

Here, we have a function addLeadingZero(num) that takes in the number as a parameter.

First, we converted the number to string using toString() method. And then using slice(1) we removed the - sign from the number.

Next using padStart() method we have added the leading zero to the given number.

In the end, we used the + operator to add the - (minus) sign back to the number and returned the value.


Other Articles You’ll Also Like:

Check if String Is a Number or Not in JavaScript

How to find exponent power of a number in JavaScript

How to write isNumber() in JavaScript?

Scroll to Top