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

How to Add Leading Zeros to Numbers in JavaScript?

Patricia Arquette
Release: 2024-12-10 18:09:10
Original
840 people have browsed it

How to Add Leading Zeros to Numbers in JavaScript?

Leading Zeros in JavaScript Numbers

In JavaScript, is there a way to automatically add leading zeros to numbers to achieve a specific string length? For instance, converting 5 to "05" with a target length of 2?

Solution:

Conversion to String

Since numbers inherently don't have leading zeros, we need to convert the number to a string first. Here's a sample function:

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

Example:

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

Alternative Approach

If the maximum number of leading zeros is known, an alternative method can be more efficient:

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

Negative Numbers

Handling negative numbers requires stripping the negative sign and re-adding it after padding:

function padWithSign(num, size) {
  if (num < 0) {
    num = -num;
    return "-" + pad(num, size);
  } else {
    return pad(num, size);
  }
}
Copy after login

The above is the detailed content of How to 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template