"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Add Leading Zeros to Numbers in JavaScript?

How to Add Leading Zeros to Numbers in JavaScript?

Posted on 2025-03-24
Browse:443

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 

Example:

pad(5, 2); // "05"

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);
}

Negative Numbers

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

function padWithSign(num, size) {
  if (num 
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3