Home > Web Front-end > JS Tutorial > How Can I Pad a Number with Leading Zeros in JavaScript?

How Can I Pad a Number with Leading Zeros in JavaScript?

DDD
Release: 2024-12-06 11:38:12
Original
411 people have browsed it

How Can I Pad a Number with Leading Zeros in JavaScript?

Padding a Number with Leading Zeros in JavaScript

When dealing with JavaScript, the need often arises to pad a number with leading zeros. For instance, the number 9 becomes "0009," and 10 becomes "0010," always adhering to a four-digit format.

Plain-Jane Method

A straightforward approach involves subtracting the number from 4 to determine the necessary number of zeros. While functional, it lacks flair.

ES2017's padStart() Method

In ES2017, the String.prototype.padStart() method offers a more elegant solution. It appends the specified character (by default, a space) to the left of the string until it reaches the desired length.

n = 9;
String(n).padStart(4, '0'); // '0009'

n = 10;
String(n).padStart(4, '0'); // '0010'
Copy after login

Generic Padding Function

In scenarios where padStart() may not be an option, a generic padding function can be utilized:

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
Copy after login

This function employs an array's ability to accept a number as an argument and create an array with that length, populated with undefined elements. When joining these elements with a zero (or other specified character), a string is generated with the appropriate number of leading zeros.

Example Usage

pad(10, 4);      // 0010
pad(9, 4);       // 0009
pad(123, 4);     // 0123

pad(10, 4, '-'); // --10
Copy after login

The above is the detailed content of How Can I Pad a Number with Leading Zeros in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template