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

How to Pad a Number with Leading Zeros in JavaScript?

Linda Hamilton
Release: 2024-12-06 15:28:16
Original
665 people have browsed it

How to Pad a Number with Leading Zeros in JavaScript?

How to Pad a Number with Leading Zeros in JavaScript

JavaScript lacks a built-in function for padding numbers with leading zeros. However, you can achieve this padding using various methods.

Solution 1: Using String.prototype.padStart()

For ES2017 and above, you can leverage the String.prototype.padStart() method:

String(n).padStart(4, '0');
Copy after login

This will pad the number n with zeros until it reaches a total length of 4. For example:

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

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

Solution 2: Using Array.prototype.join()

For pre-ES2017 browsers, you can use a combination of Array.prototype.join() and string concatenation:

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 first checks if the number's string length is already greater than or equal to the desired width. If not, it initializes an array with a length equal to the width minus the number's current length plus 1 and joins it with the zero character. This effectively creates a string of zeros of the appropriate length, which is then concatenated with the number.

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 to 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template