Javascript format number with leading zero

How to pad a number with leading zeros in JavaScript?

In this tutorial, we will learn how to pad a number with leading zeros in JavaScript.

Padding a number can be done in different ways in JavaScript. In this tutorial, we will see the two most popular ways of doing it −

Using the String padStart() Method

In JavaScript, the String object’s padStart() method is useful to pad a number with leading zeros. It takes two parameters, the first one is the total length of the targeted or desired string, and the other one is the string or character the user wants to use for padding. The number the user wants to pad must be converted to a string first to use this method.

Users can follow the syntax below to pad a number with leading zeros in JavaScript using the padStart() method.

Syntax

let number = 2 let result = number.toString().padStart(5, '0') console.log(result); // 00002

In the above syntax, the padStart() method takes 5 as the targeted string length, and “0” is the string or character by which the number should be padded.

Читайте также:  Порядок карт

Parameters

  • Targeted Length − It takes the length of the targeted string.
  • Pad String − It is the string by which the padding will be performed.

Return Type

Example

In the below given an example, we have used the String padStart() method to pad a number with leading zeros. We have made use of a button click event to pad the number.

html> body> h3> Padding a number with leading zeros in JavaScript using i> padStart() /i> method /h3> h4> Pad the number 12 with leading zeros and the total length should be 5 /h4> button onclick = "padNumber()"> Pad Number /button> h4 id = "root"> /h4> script> let root = document.getElementById('root') let number = 12 function padNumber() let result = number.toString().padStart(5, '0') root.innerHTML = "Result: " + result > /script> /body> /html>

Using the Array Object Constructor and join() Method

It is an alternative approach to pad a number. In this approach, we use the Array object constructor of JavaScript to make an array with the same number of elements as required zeros to pad the number. Then we join it with “0” to make a padding string and add it with the number.

Syntax

let number = 24 let strNumber = number.toString() let targeted_length = 5 let result = '' // padding zeros if(strNumber.length targeted_length) let padding = new Array(targeted_length - strNumber.length + 1).join('0') result = padding + strNumber >else result = strNumber >

In the above syntax, the “result” variable stores the value of the padded number, leading with zeros.

Algorithm

Step-1 − Declare a variable that stores the string of the number and also declare the targeted string length

Step-2 − If the length of the number string is less than the targeted length then,

Step-2.1 − Use the Array object constructor to make an array of length targeted_length – string number’s length + 1, and join the array elements with the character “0” using the join() method. It will be the padded string.

Step-2.2 − Concatenate the padded string and the number. It will be the result.

Step-3 − If the length of the number string is not less than the targeted length, then the number doesn’t need any padding.

Example

In the below given an example, we have used the Array object constructor and join() method to pad a number with leading zeros. We have made use of a button click event to pad the number.

html> body> h3> Padding a number with leading zeros in JavaScript using i> Array object constructor and join() /i> method /h3> h4> Pad the number 24 with leading zeros and the total length should be 5 /h4> button onclick = "padNumber()"> Pad Number /button> h4 id = "root"> /h4> script> let root = document.getElementById('root') let number = 24 let targeted_length = 5 function padNumber() let strNumber = number.toString() if(strNumber.length targeted_length) let padding = new Array(targeted_length - strNumber.length + 1).join('0') let result = padding + strNumber root.innerHTML = "Result: " + result > > /script> /body> /html>

We have learned how to pad a number with leading zeros in JavaScript using two different methods. The first approach uses the String padStart() method, which is also recommended. The second approach uses the Array object constructor and the join method to make the padding. The first approach is the standard approach, and the second is recommended if the users don’t want to use the String padStart() method.

Источник

Javascript format number with leading zero

Last updated: Jan 5, 2023
Reading time · 4 min

banner

# Add Leading Zeros to a Number in JavaScript

To add leading zeros to a number:

  1. Use the String() object to convert the number to a string.
  2. Call the padStart() method to add zeros to the start of the string.
  3. The padStart method will return a new string, padded with leading zeros.
Copied!
function padWithLeadingZeros(num, totalLength) return String(num).padStart(totalLength, '0'); > console.log(padWithLeadingZeros(3, 2)); // 👉️ "03" console.log(padWithLeadingZeros(3, 3)); // 👉️ "003" console.log(padWithLeadingZeros(3, 4)); // 👉️ "0003" console.log(padWithLeadingZeros(100, 2)); // 👉️ "100" // 👇️ Alternatively, simply use the Addition (+) operator const num = '00' + 3; console.log(num); // 👉️ "003"

The padWithLeadingZeros() function takes a number and its desired total length as parameters and pads the number with leading zeros if necessary.

The String.padStart method pads the current string with the provided string until the resulting string reaches the given length.

The padStart method takes the following 2 arguments:

Name Description
targetLength The string gets padded with the pad string up to this length.
padStart The string to pad the current string with.

The targetLength argument also takes into consideration decimal characters or a minus sign.

An easy way to think about the method is that it pads the original string to a target length with a supplied string.

Copied!
const num = 3; console.log(String(num).padStart(2, '0')); // 👉️ 03 console.log(String(num).padStart(3, '0')); // 👉️ 003 console.log(String(num).padStart(4, '0')); // 👉️ 0003

If you have a string of length 2 and you set the target length argument to 4 , the string will get padded with 2 leading zeros.

Copied!
// 👇️ "0022" console.log(String(22).padStart(4, '0'));

Make sure to convert the number to a string before using the padStart() method.

If you always want to pad the number with a specific number of leading zeros, use the number’s length to determine the target length.

Copied!
const num = 123; const str = String(num); // ✅ pad number with 2 leading zeros console.log(str.padStart(str.length + 2, '0')); // ✅ pad number with 3 leading zeros console.log(str.padStart(str.length + 3, '0'));

By adding n to the length of the number to determine the target length, we always add n leading zeros to the number.

If you convert the padded string back to a number, any of the leading zeros will automatically get dropped.

Copied!
const num = 3; const result = Number(String(num).padStart(5, '0')); console.log(result); // 👉️ 3

If the length of the number exceeds the provided target length, the entire string gets returned from the padStart method.

Copied!
function padWithLeadingZeros(num, totalLength) return String(num).padStart(totalLength, '0'); > const num = 123456; console.log(padWithLeadingZeros(num, 3)); // 👉️ "123456"

# Padding negative numbers with leading zeros

If you need to handle negative numbers, you need to add an if statement that adds the minus sign after the leading zeros have been added.

Copied!
function addLeadingZeros(num, totalLength) if (num 0) const withoutMinus = String(num).slice(1); return '-' + withoutMinus.padStart(totalLength, '0'); > return String(num).padStart(totalLength, '0'); > console.log(addLeadingZeros(3, 2)); // 👉️ "03" console.log(addLeadingZeros(-3, 3)); // 👉️ "-003"

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.

To handle negative numbers, we just had to strip the minus, add the leading zeros and add the minus to the front of the string.

# Pad a number with leading zeros using the addition (+) operator

The addition (+) operator will convert the number to a string and will add the specified number of leading zeros to the beginning of the string.

Copied!
const positive = '00' + 5; console.log(positive); // 👉️ "005" const negative = '-' + '00' + String(-5).slice(1); console.log(negative); // 👉️ "-005"

When using the addition operator with a number and a string, the number gets converted to a string and the two strings get concatenated.

We used the same approach to handle negative numbers as we did with the padStart method.

If you have to pad a number with leading zeros often, define a reusable function.

Copied!
function padWithLeadingZeros(num, n) const char = '0'; return char.repeat(n) + num; > const num = 123; console.log(padWithLeadingZeros(num, 2)); // 👉️ 00123 console.log(padWithLeadingZeros(num, 3)); // 👉️ 000123 console.log(padWithLeadingZeros(num, 4)); // 👉️ 0000123

The padWithLeadingZeros function takes a number and how many leading zeros should be added to the number as parameters.

The function uses the String.repeat method to repeat the zero n times and adds it to the beginning of the string.

Copied!
console.log('0'.repeat(3)); // 👉️ "000" console.log('0'.repeat(2)); // 👉️ "00"

You can also use a while loop to add leading zeros to a number.

# Pad a number with Leading Zeros using a while loop

This is a three-step process:

  1. Convert the number to a string.
  2. Use a while loop to iterate for as long as the string hasn’t reached the target length.
  3. Pad the string with leading zeros until it reaches the target length.
Copied!
function padWithZero(num, targetLength) let str = String(num) while (str.length targetLength) str = '0' + str > return str > const num = 5; // ✅ pad with 2 leading zeros console.log(padWithZero(num, String(num).length + 2)); // 👉️ '005' // ✅ pad with 3 leading zeros console.log(padWithZero(num, String(num).length + 3)); // 👉️ '0005' // ✅ pad with 4 leading zeros console.log(padWithZero(num, String(num).length + 4)); // 👉️ '00005'

The padWithZero() function is very similar to the padStart method.

It takes a number and the desired target length as parameters and pads the number with leading zeros to the specified length.

The first step is to convert the number to a string.

The while loop iterates for as long as the string’s length is less than the desired target length.

On each iteration, we use the addition (+) operator to add a leading zero to the string.

Once the string reaches the desired target length, the condition in the while loop is no longer met.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to Output Numbers With Leading Zeros in JavaScript?

girl crawling on white floor while smiling

Sometimes, we want to output numbers with leading zeroes in our JavaScript programs.

In this article, we’ll look at how to create numbers with leading zeroes with JavaScript.

String.prototype.padStart

The JavaScript string’s padStart method lets us add characters we want to a string until it reaches a given length.

For instance, we can write:

const padded = (123).toString().padStart(5, '0') console.log(padded) 

We call toString on the number to convert it to a string.

Then we call padStart with 5 to pad the string to length 5.

And we pass in ‘0’ to pad the number with leading 0’s.

Therefore, padded is ‘00123’ .

Write Our Own Code

We can also write our own code to pad a number string with leading zeroes.

For instance, we can write:

const zeroPad = (num, places) => < const numZeroes = places - num.toString().length + 1; if (numZeroes >0) < return Array(+numZeroes).join("0") + num; >return num > console.log(zeroPad(5, 2)) console.log(zeroPad(5, 4)) console.log(zeroPad(5, 6)) 

We create the zeroPad function that takes the num and places parameters.

num has the number we want to pad with leading zeroes.

places is the number of decimal places that we want to pad to.

In the function, we compute the numZeroes variable, which is the number of leading zeroes we want to add to make the string the length set by places .

We compute that by substracting places with num.toString().length plus 1.

This subtracts the final number of places with the length of the number string plus 1.

We add 1 so that we create the correct sized array since we want to add zeroes in between the array entries with join .

Then if numZeroes is bigger than 0, we return a string with leading zeroes by creating an array, then calling join with 0 to create the zero string, and then concatenating that with the num value.

Otherwise, we return num itself.

So the console log should log:

Conclusion

We can pad our JavaScript nuinmber strings with leading zeroes with the padStart method or write our own code to do so.

Источник

Оцените статью