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

How Can I Add Leading Zeros to Numbers in JavaScript?

DDD
Release: 2024-12-08 10:58:11
Original
218 people have browsed it

How Can I Add Leading Zeros to Numbers in JavaScript?

Prepending Leading Zeros to Numbers in JavaScript

Is there a way to add leading zeros to numbers in order to obtain a string with a consistent length? For instance, the number 5 should be converted to "05" if two digits are specified.

Solution:

To add leading zeros, you need to convert the number into a string because numbers don't recognize leading zeros. Here's one way to achieve this:

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

For example, if you want to add two leading zeros to the number 5:

pad(5, 2); // returns "05"
Copy after login

However, this function assumes that you'll never need more than 10 leading zeros. If you anticipate larger values, you can use a different approach:

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

For example:

pad(5, 6); // returns "000005"
Copy after login

Note that if you need to handle negative numbers, you'll need to remove and re-add the negative sign after padding.

The above is the detailed content of How Can I Add Leading Zeros to Numbers 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