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.
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.
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"
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.
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"