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"
@GAZ082
Copy link

GAZ082 commented Dec 22, 2017

Handy! Thank you!

@Enelar
Copy link

Enelar commented Mar 4, 2018

You have bug with negative numbers

Number.prototype.pad = function(size) {
  var sign = Math.sign(this) === -1 ? '-' : '';
  return sign + new Array(size).concat([Math.abs(this)]).join('0').slice(-size);
}

@rroossyyiidd
Copy link

Thanks a lot!

@Utshab500
Copy link

Utshab500 commented Apr 4, 2018

This is very useful. I have one request. Can you please explain a bit the expression s.length < (size || 2) ? I did not understand why 2 is there?

@marcinappgo
Copy link

@Utshab500 I think 2 is a default size value.

@Fallibilist
Copy link

@ColinWa
Copy link

ColinWa commented Jul 20, 2018

@endel This is awesome.
@Fallibilist, Thanks a million

@david-kominek
Copy link

Note: padStart is not compatible with any version of Internet Explorer

@Paulofsr
Copy link

Thanks!

@horroona
Copy link

Thanks a lot
I use padStart() and it works fine

@stratboy
Copy link

Thank you, and thank you @Enelar

@tomcarbon
Copy link

Thank You

@knoxcard
Copy link

knoxcard commented Oct 9, 2018

padStart() for the win!

@renoirb
Copy link

renoirb commented Feb 14, 2019

I came around here and noticed something I ought to tell.
Please don't mutate your prototype chain!

Don't do Number.prototype.pad = function(n) { /* ... */ }

Create a function and a module instead.

I'm not a JS Runtime expert, but here is an MDN link about it

@little-einstien
Copy link

superb bro your a warrior !

@imanabu
Copy link

imanabu commented Jul 26, 2019

     `${n+100}`.substring(1)

@closetothe
Copy link

     `${n+100}`.substring(1)

Hahah, amazing!

@SynCap
Copy link

SynCap commented Jan 19, 2020

@kl3sk: we don't looking for easy ways!

Disadvantages of String.padStart()

  • works only in modern browsers and environments;
  • don't care about negative
  • works only on String primitives not a Number
(-4+'').padStart(7,'0')
"00000-4"

Originally presented here function by @endel do the same.

Our Overengineering but less headache way:

/** ES2015+ -- ultra-fast
@param n <Number> what to pad left with
@param z <Number> (zeros :) ) width which pad to
@param s <String> (sign :) ) char to pad with, of course may be some like that 'oO'
@return <String>
@example
	pz(7, 15, 'oO')
	// ==> "oOoOoOoOoOoOoO7"

	pz(-1005007, 20)
	// ==> "-00000000000001005007"
*/
const pz = (n, z = 2, s= '0') =>
	(n+'').length <= z ? (['','-'])[+(n<0)] + (s.repeat(z) + Math.abs(n)).slice(-1*z) : n + '';

/** v2, do the same but can work in carton boxes
*/
function pz(n, z, s) {
	function rpt(z,s) {acc='';for(i=0;i<z;i++) acc+=s; return acc}
	var z= z || 2, s = s || '0';
	if ( (n+'').length <= z  ) 
		return  (['','-'])[+(n<0)] + (rpt(z,s) + Math.abs(n)).slice(-1*z) 
	else
		return  n + '';
}

Features:

  • cares about negative numbers
  • cares about length -- don't cut just pads
  • works with Numbers
  • v2 works in legacy trash cans even in MS IE 3.1 and Rhino
  • have a short way (defaults)

@GSKang94
Copy link

Thanks a ton!!

@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