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!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/add-leading-trailing-zeroes-javascript/” title=”Add Leading & Trailing Zeroes To Numbers In Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

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.

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA 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 *