How To Add Leading & Trailing Zeroes To Numbers In Javascript

Welcome to a short tutorial on how to add leading and trailing zeroes to numbers in Javascript. So you have some numbers that require padding of zeroes?

The easy way to add leading or trailing zeroes in Javascript is to:

  1. Concatenate the number with a string of zeroes.
    • var num = "000" + 123;
    • var num = 123.45 + "000";
  2. Or use the string pad functions.
    • var num = "123".padStart(5, 0);
    • var num = "123.45".padEnd(8, 0);

That covers the basics, but let us walk through a few more examples – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Pad Zeroes Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

PAD WITH ZEROES

All right, let us now go into the examples of padding a number with leading and trailing zeroes.

 

EXAMPLE 1) EASY LEADING & TRAILING ZEROES

1-easy.html
// (A) THE NUMBERS
var numA = 123;
var numB = 123.45;
 
// (B) STRING CONCAT
console.log("000" + numA);
console.log(numB + "000");
 
// (C) PAD STRING
console.log(numA.toString().padStart(5, 0));
console.log(numB.toString().padEnd(8, 0));

As in the introduction above, the easiest way to pad a number with zeroes is to either –

  • Concatenate with a string of zeroes.
  • Or convert the number to string, then use the pad string functions.

 

 

EXAMPLE 2) MANUAL PAD LEADING & TRAILING ZEROES

2-pad-zero.js
// (A) PAD WITH ZEROES
//   NUM : THE ORIGINAL NUMBER
//   LEAD : TOTAL NUMBER OF DIGITALS ALLOWED (WHOLE NUMBERS)
//   TRAIL : TOTAL NUMBER OF DIGITALS ALLOWED (DECIMAL NUMBERS)
function padZero (num, lead, trail) {
  // (A1) CONVERT NUMBER TO STRING
  var cString = num.toString();

  // (A2) GET NUMBER OF DIGITS
  var cWhole, cDec, cCheck = cString.indexOf(".");

  // NO DECIMAL PLACES, A WHOLE NUMBER
  if (cCheck == -1) {
    cWhole = cString.length;
    cDec = 0;
    cString += ".";
  }
  // IS A DECIMAL NUMBER
  else {
    cWhole = cCheck;
    cDec = cString.substr(cCheck+1).length;
  }

  // (A3) PAD WITH LEADING ZEROES
  if (cWhole < lead) {
    for (let i=cWhole; i<lead; i++) { cString = "0" + cString; }
  }

  // (A4) PAD WITH TRAILING ZEROES
  if (cDec < trail) {
    for (let i=cDec; i<trail; i++) { cString += "0"; }
  }

  return cString;
}

// (B) TEST
// (B1) WHOLE NUMBER
var first = padZero(123, 5, 3);
console.log(first); // 00123.000

// (B2) DECIMAL
var second = padZero(123.45, 5, 3);
console.log(second); // 00123.450

Once upon a time in the Dark Ages of the Internet, this is how we pad a number with zeroes… Essentially:

  • A1 – Convert the number into a string first.
  • A2 – Split the number into “whole numbers” and “decimals”.
  • A3 & A4 – Add the leading and/or trailing zeroes as required.

 

 

EXTRA) REMOVE ZEROES

3-remove-zero.js
// (A) PARSE FLOAT & INT
console.log(parseFloat("0123.4500")); // 123.45
console.log(parseInt("0123.4500")); //123

// (B) USING REGULAR EXPRESSION
// Credits: https://stackoverflow.com/questions/594325/input-field-value-remove-leading-zeros
function removeZero (num) {
  return num.replace(/^0+(?!\.|$)/, '');
}
console.log(removeZero("000.00")); // 0.0
console.log(removeZero("00000")); // 0
console.log(removeZero("012.30")); // 12.30

Finally, a small extra to do the opposite of removing zeroes –  Simply use parseFloat() or parseInt() and that’s it. But if you want a “smarter remove zero” – Using regular expressions is the only way to go.

 

USEFUL BITS & LINKS

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

 

SUMMARY

Function Description Reference
.toString() One of the most important functions to convert number or decimal to a string – Pad with zeroes, add commas or period. Click Here
.indexOf("CHARACTER") Finds the position of the given character in a string. Click Here
STRING.padStart(LENGTH, WITH) Pad the start of string with the given character. Click Here
STRING.padEnd(LENGTH, WITH) Pad the end of string with the given character. Click Here
parseInt(STRING) Parse a string into an integer. Click Here
parseFloat(STRING) Parse a string into a float. Click Here

 

INFOGRAPHIC CHEAT SHEET

Add Leading & Trailing Zeroes (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *