How to add zeros before number in javascript

Updated May 30, 2024#javascript#numbers#strings

Adding leading zeros to a number is often necessary in scenarios where the representation of the number needs to have a fixed width or format.

  • When dealing with dates and times (“09:05”)
  • Serial numbers or identifiers need consistent length for sorting or display purposes.
  • Numbers are often displayed in tables or lists with a fixed width to improve alignment.

In JavaScript, you can add leading zeros to a number by converting it to a string and then using string manipulation functions. These methods return strings, not numbers. If you need to perform mathematical operations, convert the padded string back to a number.

  1. Using padStart() method, which adds another string (called the padding) to the beginning of the original string until it reaches a specified length.

This method takes two arguments: the target length of the padded string, and the string to use as the padding. If the padding string is too long, it will be truncated. If the target length is less than or equal to the original string length, the original string will be returned without any changes.

Here’s an example that pads the number 5 with zeros until it has 3 digits:

var num = 5;
var paddedNum = num.toString().padStart(3, "0");
console.log(paddedNum); //=> "005"
  1. Using slice() method, which extracts a part of a string and return it as a new string. The method takes two arguments: the start index and the end index of the part to extract. The start index is inclusive, but the end index is exclusive. You can use negative indexes to count from the end of the string.

You can pad leading zeros to a number by concatenating the number with a string of zeros, and then slicing the desired length from the end.

Number.prototype.pad = function (n) {
  return (new Array(n).join('0') + this).slice((n || 2) * -1);
};

const num = 4;
console.log(num.pad(4)); //=> "0004"

In this example, the pad() function accepts an argument specifying the desired length of the resulting string. If no argument is provided, it defaults to 2.

  1. Using a loop. First you need to convert the number to a string and then calculates the number of leading zeros needed to reach the specified width. Finally, it adds the leading zeros using a loop and returns the resulting string.
Number.prototype.pad = function (n) {
  let numString = this.toString();
  let zerosToAdd = n - numString.length;

  for (let i = 0; i < zerosToAdd; i++) {
    numString = "0" + numString;
  }

  return numString;
};

const num = 4;
console.log(num.pad(4)); //=> "0004"