Skip to main content

How to Add Leading Zeros to a Number in JavaScript

A common formatting requirement in programming is to pad a number with leading zeros to create a fixed-width string. This is essential for creating correctly sorted filenames (e.g., file-001.txt), displaying timer values (01:05), or formatting data for reports. The modern and standard way to achieve this is with the String.prototype.padStart() method.

This guide will teach you how to use padStart() to format numbers, how to handle negative numbers, and the important distinction between padding to a total length versus adding a specific number of zeros.

The padStart() method is the definitive, built-in tool for this job. It pads the current string with another string (in our case, '0') until the resulting string reaches the given length. The padding is applied from the start of the string.

The logic:

  1. Convert the number to a string using String(num).
  2. Call padStart() on the string with two arguments: the targetLength and the padString.

Example of Syntax:

String(myNumber).padStart(targetLength, '0')

Padding to a Total Length

This is the most common use case. You have a desired total width for your string, and you want to pad any shorter numbers to meet that width.

For example, we want to format numbers so they are always 3 digits long (e.g., 5 -> "005", 42 -> "042").

// Problem: How to format these numbers to be 3 digits long?
const num1 = 5;
const num2 = 42;

Solution:

function padToThreeDigits(num) {
// Convert to string and pad to a total length of 3 with '0'.
return String(num).padStart(3, '0');
}

// Example Usage:
console.log(padToThreeDigits(5)); // Output: "005"
console.log(padToThreeDigits(42)); // Output: "042"
console.log(padToThreeDigits(123)); // Output: "123"

// If the number is already longer than the target, it is not changed.
console.log(padToThreeDigits(1234)); // Output: "1234"
note

Important: padStart() returns a string. If you convert this string back to a number (Number('005')), the leading zeros will be lost. This method is for display and formatting, not mathematical operations.

Adding a Specific Number of Leading Zeros

If your goal is to add a specific number of zeros to the front of a number, regardless of its length, you can calculate the targetLength dynamically.

Solution:

function addLeadingZeros(num, numberOfZeros) {
const numStr = String(num);
const targetLength = numStr.length + numberOfZeros;
return numStr.padStart(targetLength, '0');
}

// Example Usage:
// Always add 2 leading zeros
console.log(addLeadingZeros(123, 2)); // Output: "00123"
console.log(addLeadingZeros(5, 2)); // Output: "005"

Handling Negative Numbers

A common problem with padStart is that it includes the minus sign (-) as part of the string's length.

// This doesn't produce the desired "-005"
console.log(String(-5).padStart(3, '0')); // Output: "0-5"

The padding is applied to the start of the entire string "-5".

The solution is to handle negative numbers correctly by handling the minus sign separately.

function padNumber(num, totalLength) {
if (num < 0) {
// Slice off the minus sign, pad the rest, then add the sign back.
return '-' + String(num).slice(1).padStart(totalLength, '0');
}
return String(num).padStart(totalLength, '0');
}

// Example Usage:
console.log(padNumber(5, 3)); // Output: "005"
console.log(padNumber(-5, 3)); // Output: "-005"

A Note on Older, Verbose Methods

Before padStart() was introduced in ES2017, this task was solved with more verbose methods, such as while loops or the "add and slice" trick (('000' + num).slice(-3)). While these still work, they are less readable and more prone to errors than the modern, built-in padStart() method. For any modern project, padStart() is the clear best practice.

Conclusion

Adding leading zeros to a number is a simple formatting task with a clear, modern solution in JavaScript.

  • The String.prototype.padStart() method is the definitive and recommended best practice. It is concise, readable, and explicitly designed for this purpose.
  • The core syntax is String(num).padStart(targetLength, '0').
  • Be mindful of negative numbers, as the minus sign is part of the string length. You must handle the sign separately for correct formatting.