Categories
JavaScript Answers

How to Format Numbers by Prepending a 0 to Single-Digit Numbers in JavaScript?

Spread the love

Sometimes, we may want to format our numbers by pretending zeroes before it until it matches a given length.

In this article, we’ll look at how to format numbers by padding a number with leading zeroes until it meets a given length.

Number.prototype.toLocaleString

One way to pad a number with leading zeroes is to use the toLocaleString method.

It lets us pad a number with leading zeroes until it reaches a minimum length.

For instance, we can write:

const formattedNumber = (2).toLocaleString('en-US', {
  minimumIntegerDigits: 2,
  useGrouping: false
})
console.log(formattedNumber)

To pad the number 2 with leading zeroes until it’s 2 digits long.

minimumIntegerDigits is set to 2 so that the returned number string will be at least 2 characters long.

useGrouping set to false removes any digit grouping separator for the given locale.

Therefore, formattedNumber is '02' .

Write Our Own Function

We can also write our own function to pad a number string until it meets the given length.

For instance, we can write:

function leftPad(number, targetLength) {
  let output = number.toString();
  while (output.length < targetLength) {
    output = '0' + output;
  }
  return output;
}

const formattedNumber = leftPad(2, 2)
console.log(formattedNumber)

We create the leftPad function that takes the number to format and the targetLength to pad to as arguments.

We convert the number to a string with the toString method and assign it to output.

Then we use a while loop to prepend the output with zeroes until the targetLength is met.

Then we return the output string.

So when we call leftPad with 2 and 2, we get '02' .

String.prototype.padStart

Another way to pad a number string with zeroes until a given length is to use the string padStart method.

For instance, we can write:

const formattedNumber = (2).toString().padStart(2, "0");
console.log(formattedNumber)

We call toString on 2 to convert it to a string.

Then we call padStart on it with the length that we want to pad to and the character to pad the string with.

padStart prepends the string with the characters in the 2nd argument repeatedly until the length in the first argument is met.

Therefore, formattedNumber is the same as the other examples.

Conclusion

We can format numbers with leading zeroes until it meets a given length with JavaScript with a few simple methods or operations.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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