# How to format a number with leading zeros in javascript?

## Question:

Hello I need to convert an integer to a string and in turn define a certain length of characters to the number, in case the length is less than it is filled with leading zeros, an example

``````324  ->   00324  // suponiendo que haya definido en 5 la longitud
``````

In python there was a specific function that did this called zfill

``````>>> '234'.zfill(5)
00234
``````

There is an equivalent in javascript or what would be a function that does the same.

Greetings

Thinking about the logic of the Python function I made this function, which receives as parameters your number and the desired width (the length, as you defined in your question).

If the width is less than or equal to the length of the number string, the number is returned.

Otherwise, X zeros are placed before the number, where X is the subtraction between the width given as a parameter and the length of the number's string.

Additionally, and replicating what happens in the Python function, this function contemplates the case of using the function on a negative number. To do this, we work with absolute values, so that, if your number is negative, the sign `-` is added to the beginning of the string, the zeros to be added or not, and the absolute value of the number at the end.

``````function zfill(number, width) {
var numberOutput = Math.abs(number); /* Valor absoluto del número */
var length = number.toString().length; /* Largo del número */
var zero = "0"; /* String de cero */

if (width <= length) {
if (number < 0) {
return ("-" + numberOutput.toString());
} else {
return numberOutput.toString();
}
} else {
if (number < 0) {
return ("-" + (zero.repeat(width - length)) + numberOutput.toString());
} else {
return ((zero.repeat(width - length)) + numberOutput.toString());
}
}
}

console.log(zfill(324, 2)); // 324
console.log(zfill(324, 3)); // 324
console.log(zfill(324, 4)); // 0324
console.log(zfill(324, 5)); // 00324
console.log(zfill(324, 10)); // 0000000324
console.log(zfill(-324, 5)); // -0324``````
Scroll to Top