Skip to content

Instantly share code, notes, and snippets.

@SynCap
Created June 30, 2021 05:03
Show Gist options
  • Save SynCap/66210a3267e2279a595c540277e756bc to your computer and use it in GitHub Desktop.
Save SynCap/66210a3267e2279a595c540277e756bc to your computer and use it in GitHub Desktop.
Pad Number left with care about sign

numberPad.js

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"

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
	np(7, 15, 'oO')
	// ==> "oOoOoOoOoOoOoO7"

	np(-1005007, 20)
	// ==> "-00000000000001005007"
*/
const np = (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 np2(n, z, s) {

	var z= z || 2, s = s || '0';

	function rpt(z,s) {acc='';for(i=0;i<z;i++) acc+=s; return acc}

	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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment