Skip to content

Instantly share code, notes, and snippets.

@SynCap
Last active March 23, 2020 11:55
Show Gist options
  • Save SynCap/47ed30610f9bb6b63d6823dc2c2d720b to your computer and use it in GitHub Desktop.
Save SynCap/47ed30610f9bb6b63d6823dc2c2d720b to your computer and use it in GitHub Desktop.
Vanilla Javascript number padding functions

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"

> (400.302).padStart(9, '0')
Uncaught TypeError: 400.302.padStart is not a function at <anonymous>:1:11

(0005).padStart(3, '0')
Uncaught TypeError: 5.padStart is not a function at <anonymous>:1:8

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)
/** 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 pn = (n, z = 2, s= '0') =>
(n+'').length <= z ? (['','-'])[+(n<0)] + (s.repeat(z) + Math.abs(n)).slice(-1*z) : n + '';
// ** Legaacy version do the same but can work in carton boxes **
function pn_legacy(n, z, s) {
var z= z || 2, s = s || '0';
return (n+'').length <= z ? (['','-'])[+(n<0)] + (s.repeat(z) + Math.abs(n)).slice(-1*z) : n + '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment