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

How Can I Pad Numbers with Leading Zeros in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 09:41:10409browse

How Can I Pad Numbers with Leading Zeros in JavaScript?

Padding Numbers with Leading Zeros in JavaScript

Original Question:

Can JavaScript be used to pad a number with leading zeros to a specified width? For example, a number like 9 should be padded to "0009" with three leading zeros.

Solution:

ES2017 Update:

  • String.prototype.padStart(): This built-in method allows padding a string with a specified number of characters at the beginning:

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

Legacy Approach:

  • Custom Function: If ES2017 features are not available, a custom function can be created to pad the number:

    function pad(n, width, z) {
    z = z || '0';
    n = n + '';
    return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }
  • This function takes three parameters: the number to pad (n), the desired width (width), and an optional padding character (z, defaults to '0').
  • It converts the number to a string and checks its length against the desired width.
  • If the number is shorter than the desired width, the function creates an array with the required number of elements, filled with the padding character.
  • The array elements are joined into a string and prepended to the number to achieve the desired padding.

Example Usage:

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

pad(10, 4, '-'); // --10

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

Statement:
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