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

How to Pad Numbers with Leading Zeros in JavaScript?

Patricia Arquette
Release: 2024-12-09 12:34:11
Original
810 people have browsed it

How to Pad Numbers with Leading Zeros in JavaScript?

Padding Numbers with Leading Zeros in JavaScript

In JavaScript, it can be necessary to prepend leading zeros to numbers to achieve a string of a specified length. Here are solutions:

Convert Number to String and Pad with Zeros

One approach is to convert the number to a string and then add leading zeros as needed:

function pad(num, size) {
    num = num.toString();
    while (num.length < size) num = "0" + num;
    return num;
}
Copy after login

For example, pad(5, 2) would return "05".

Utilize Placeholder String

Another option is to utilize a placeholder string that contains the desired number of zeros:

function pad(num, size) {
    var s = "000000000" + num;
    return s.substr(s.length-size);
}
Copy after login

In this case, pad(5, 2) would also return "05".

Considerations for Negative Numbers

If negative numbers are involved, you may need to handle them separately. This can be done by stripping the negative sign and re-adding it after padding:

function pad(num, size) {
    if (num < 0) {
        num = -num;
        return "-" + pad(num, size);
    }
    num = num.toString();
    while (num.length < size) num = "0" + num;
    return num;
}
Copy after login

The above is the detailed content of How to 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