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
Release: 2024-12-03 09:41:10
Original
352 people have browsed it

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'
    Copy after login

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;
    }
    Copy after login
  • 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
Copy after login

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!

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