js add zeros before number

How to Add Zeros Before a Number in JavaScript

If you want to add zeros before a number in JavaScript, you can use the padStart() method. This method adds a specified number of characters at the beginning of a string.

Syntax:

string.padStart(targetLength [, padString])
  • targetLength: The length of the resulting string once the padding is applied. If this value is less than the original string length, no padding will be added.
  • padString (optional): The string to use for padding. The default is whitespace.

Here's an example:


let num = '5';
num = num.padStart(3, '0'); // Output: '005'

In this example, we have a number 5 and we want to add zeros before it to make it a three-digit number. We use the padStart() method and pass the target length as 3 and the pad string as '0'. The resulting string is '005'.

If you have a number that is already a string, you can convert it to a number and then use the toString() method to convert it back to a string with padded zeros. Here's an example:


let num = '5';
let paddedNum = (+num).toString().padStart(3, '0'); // Output: '005'

In this example, we convert the string '5' to a number using the + operator. Then, we convert the number back to a string using the toString() method and apply the padStart() method to add zeros before the number.

Another way to add zeros before a number in JavaScript is to use the repeat() method. This method creates a new string by repeating a specified string a certain number of times. Here's an example:


let num = '5';
let zeroString = '0'.repeat(3 - num.length);
let paddedNum = zeroString + num; // Output: '005'

In this example, we first calculate the number of zeros we need to add by subtracting the length of the number from the target length. We use the repeat() method to create a string of zeros with the calculated length. Then, we concatenate the zero string and the original number to get the padded number.

Conclusion:

Adding zeros before a number in JavaScript is easy using the padStart() method. You can also use other methods like toString() and repeat() to achieve the same result.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe