Skip to content

Instantly share code, notes, and snippets.

@endel
Last active August 1, 2023 11:54
Show Gist options
  • Star 89 You must be signed in to star a gist
  • Fork 17 You must be signed in to fork a gist
  • Save endel/321925f6cafa25bbfbde to your computer and use it in GitHub Desktop.
Save endel/321925f6cafa25bbfbde to your computer and use it in GitHub Desktop.
Simplest way for leading zero padding in JavaScript
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
(1).pad(3) // => "001"
(10).pad(3) // => "010"
(100).pad(3) // => "100"
@hasanTheBest
Copy link

A stitch in time saves nine. Thanks

@n3y
Copy link

n3y commented Mar 22, 2020

@SynCap:

pz(-100, 4);   // '-100'
pz(-100, 5);   // '-00100'

@SynCap
Copy link

SynCap commented Mar 23, 2020

@n3y: thnx

now:

> pz(-100, 4)
"-0100"
> pz(-100, 5)
"-00100"
> pz(-100, 3)
"-100"
> pz(-100, 2)
"-100"

@TheULi
Copy link

TheULi commented Mar 23, 2020

@SynCap
the repeat function isn't supported by IE < Version 12 (Edge)

I'm looking for something that works with decimals, eg. 4.5 -> 004.5 or 4.543 -> 004.543

@olizh
Copy link

olizh commented Mar 25, 2020

Thanks!

@hutiwephy
Copy link

Number.prototype.pad = function(size) {
    var s = String(this);
    var getsize = ()=>{ var j = 0, fc = false; for(var i=0; i<s.length; i++){ if(!fc){if(s.charAt(i) == '.'){ fc = true; }else{ j++; }}} return j; };
    //console.log(getsize());
    while (getsize() < (size || 2)) {s = "0" + s;}
    return s;
}

applied fix to prevent decimal count on float type

@Stratoff
Copy link

"str".split("").fill("*", 0, -1).join("")
This is useful if you want to mask a string

@hafiz-bs23
Copy link

padStart() for the win!

Only without IE

@Khazl
Copy link

Khazl commented Jun 28, 2021

zeroPad(number) {
    return number > 9 ? number : '0' + number;
 }

@Ravilochan
Copy link

Wow, Thank you. How can I export this function & Import it to use it in other files?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment