JavaScript Pad a number with leading zeros
Last Updated :
12 Jan, 2023
The String prototype property is used to pad a number with leading zeros. This property allows for adding new properties and methods to existing object types.
Syntax:
object.prototype.name = value
Return value: It returns a reference to the String.prototype object.
Example 1: This example adds leading zeros to a number by creating a function and inside this function, if the number is less than the width provided then it adds the leading zeros.
html
< h1 style = "color:green;" >
GeeksforGeeks
</ h1 >
< p id = "GFG_UP" style = "font-size: 16px;" ></ p >
< button onclick = "gfg_Run()" >
click here
</ button >
< p id = "GFG_DOWN" style="color:green;
font-size: 20px; font-weight: bold;">
</ p >
< script >
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
var num = 2213;
el_up.innerHTML = 'Number = ' +num;
function pad(n, width) {
n = n + '';
return n.length >= width ? n :
new Array(width - n.length + 1).join('0') + n;
}
function gfg_Run() {
el_down.innerHTML = pad(num, 7);
}
</ script >
|
Output:
JavaScript Pad a number with leading zeros
Example 2: This example adds leading zeros to a number by creating a prototype pad. In this example we can pass a string to the object, whatever we want to pad with the number.
html
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< p id = "GFG_UP" style = "font-size: 16px;" ></ p >
< button onclick = "gfg_Run()" >
click here
</ button >
< p id = "GFG_DOWN" style="color:green;
font-size: 20px; font-weight: bold;">
</ p >
< script >
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
var num = '2213';
el_up.innerHTML = 'Number = ' + num;
String.prototype.pad = function(String, len) {
var str = this;
while (str.length < len )
str = String + str;
return str;
}
function gfg_Run() {
el_down.innerHTML = num .pad("0", 9);
}
</script>
|
Output:
JavaScript Pad a number with leading zeros
Share your thoughts in the comments
Please Login to comment...