Borislav Hadzhiev
Mon Mar 07 2022·2 min read
Photo by Benjamin Combs
To add leading zeros to a number in TypeScript:
padStart()
method to add zeros to the start of the string.padStart
method returns a new string with the specified pad string
applied from the start.function addLeadingZeros(num: number, totalLength: number): string { return String(num).padStart(totalLength, '0'); } console.log(addLeadingZeros(5, 2)); // 👉️ "05" console.log(addLeadingZeros(5, 3)); // 👉️ "005" console.log(addLeadingZeros(5, 4)); // 👉️ "0005" console.log(addLeadingZeros(100, 2)); // 👉️ "100" // ✅ or use the Addition (+) operator const num = '00' + 3; console.log(num); // 👉️ "003"
We passed the following 2 parameters to the String.padStart method.
To be able to use the padStart
method, we had to convert the number to a
string.
0005 === 5
. JavaScript (and TypeScript) don't keep insignificant leading zeros around.This is why we explicitly set the
function's
return type to string
.
If the length of the string exceeds the provided target length, the entire
string gets returned from the padStart
method.
if
statement that adds the minus sign after the leading zeros have been added.function addLeadingZeros(num: number, totalLength: number): string { if (num < 0) { const withoutMinus = String(num).slice(1); return '-' + withoutMinus.padStart(totalLength, '0'); } return String(num).padStart(totalLength, '0'); } console.log(addLeadingZeros(5, 2)); // 👉️ "05" console.log(addLeadingZeros(-5, 3)); // 👉️ "-005"
We added an if
statement to check if a negative number is provided to the
function.
Note that we deliberately don't include the minus sign in the target length for the new string.
An alternative and perhaps simpler approach is to use the addition (+) operator.
const positive = '00' + 8; console.log(positive); // 👉️ "008" const negative = '-' + '00' + String(-8).slice(1); console.log(negative); // 👉️ "-008"
We used the exact same approach to handle negative numbers as we did with the
padStart
method.