How To Pad A Number With Leading Zeros In JavaScript

How to Pad a number with Leading Zeros in JavaScript

A standardized technique for padding strings and converting numbers to strings is supported by JavaScript. This lesson will introduce different methods to pad a number with leading zeros in JavaScript, including negative values.

How to pad a number with leading zeros in JavaScript

Add leading zeros directly to a string

As we are able to convert a leading zero number to an actual value, it’s best to instantiate a new string containing your number and leading zeros.

The following examples will work:

const num = 1;
console.log('0000'+num);

Or

const num = 1;
const zeroleading = '0000' + num;
console.log (zeroleading );

Output

00001

The cool thing about Javascript is that it’s crazy. It can add a string and a given number together. This doesn’t cause an error. Its final return is a string. However, if you need to display it, this should be more than enough for your problem.

Try checking the final result data type:

const num = 1;
const zeroleading = '0000' + num;
console.log("Data type is: " + typeof(zeroleading));

Output

Data type is: string

This can be a bit inconvenient. If your data type needs are numbers, then you are in trouble. Your original data has been lost, so see the 2nd method below

Combination toString() and padStart()

In this method, we will use the built-in function below to pad a number with leading zeros:

toString()

Syntax:

toString()

Compile a string that represents the object invoked. All data types when using this method are converted to string type.

padStart()

Syntax:

padStart(target, str)

Parameters:

  • target: Pad object, if longer than the str.length, it is set by default.
  • str: Is an optional parameter – the pad string.

Pad the current string with another string once or multiple times until reaching the given length. The padding is applied from the start of the current string.

Our code will execute as follows:

const padNumber = 3;
console.log(padNumber.toString().padStart(5, '0'));

Output

00001

Try checking the final result data type:

const padNumber = 3;
console.log(padNumber.toString().padStart(5, '0'));
console.log("Data type is: " + typeof(padNumber));

Output

Data type is: number

So when applying this method and your project, it will keep your data type even if you manipulated the string.

Summary

In conclusion, you have known the ways to pad a number with leading zeros in JavaScript using built-in methods in JavaScript. JS is a dynamic language in dealing with different types of data. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *