This article explains in a simple way how to use JavaScript’s slice() method to display numbers with leading zeros to a specified number of digits. This technique is very useful for formatting form inputs and display outputs.
What is Zero Padding?
Zero padding refers to adding zeros before a number to match a specific format. For example, it is often used when formatting dates, times, or serial numbers.
Styling with CSS
It is important to apply a clear and readable style to the display area. Below is an example of CSS for styling the output area (#output) of zero-padded numbers.
<style>
body {
margin: 0;
padding: 0;
font-size: 20px;
line-height: 1.8em;
text-align: center;
}
h1{
text-align: center;
font-size: 20px;
line-height: 1.8em;
padding: 15px 0;
}
#output{
color: red;
font-weight: bold;
}
</style>
Building the HTML Markup
The numbers displayed to the user should be placed inside properly marked-up HTML elements. Below is the basic HTML structure for displaying zero-padded numbers.
<h1>Pad a number with leading zeros to the specified digit length.</h1>
<div>Number “123456” with a 10-digit specification,<br>the zero-padded output result is shown below.</div>
<br>
<div id="output"></div>
Implementation with JavaScript slice()
The slice() method is generally used to extract part of an array, but here we apply it to string formatting. The following function digitAlignment() takes a number and digit length, and pads the number with zeros to match the specified digit length. slice() is a method that returns part of an array (or string) within a specified range. slice(-digit) returns the last specified number of digits.
<script>
// num: number, digit: digit length
function digitAlignment(num, digit){
var zeroFormat = (Array(digit).join('0') + num).slice(-digit);
return zeroFormat;
}
// Display the output result (return value) in id="output"
document.getElementById('output').innerHTML=digitAlignment(123456, 10);
</script>
Demo Page: Display Numbers with Leading Zeros Using JavaScript slice()
Not just theory—by seeing a working demo, you can deepen your understanding. From the link below, you can check a demo page that uses the slice() method for zero padding.
Demo page to display numbers with leading zeros using JavaScript slice()
Conclusion
In this article, we explained how to display zero-padded numbers using JavaScript’s slice(). By mastering this technique, you can format any number display in a professional way.
※If you reuse this, please do so at your own responsibility.
Do not reuse the Google Analytics tag in the head of the demo page.