How can I pad a value with leading zeros?

  1. Home
  2. javascript
  3. How can I pad a value with leading zeros?

What is the recommended way to zerofill a value in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I’m wondering if there is a more direct way to do this?

Note: By “zerofilled” I mean it in the database sense of the word (where a 6-digit zerofilled representation of the number 5 would be “000005”).

First answer

Note to readers!

As commenters have pointed out, this solution is “clever”, and as
clever solutions often are, it’s memory intensive and relatively
slow. If performance is a concern for you, don’t use this solution!

Potentially outdated: ECMAScript 2017 includes String.prototype.padStart and Number.prototype.toLocaleString is there since ECMAScript 3.1. Example:

var n=-0.1;
n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false})

…will output “-0000.10”.

// or 
const padded = (.1+"").padStart(6,"0");

…will output “-0000.1”.

A simple function is all you need

function zeroFill( number, width )
  width -= number.toString().length;
  if ( width > 0 )
    return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
  return number + ""; // always return a string

you could bake this into a library if you want to conserve namespace or whatever. Like with jQuery’s extend.

Second answer

Simple way. You could add string multiplication for the pad and turn it into a function.

var pad = "000000";
var n = '5';
var result = (pad+n).slice(-pad.length);

As a function,

function paddy(num, padlen, padchar) {
    var pad_char = typeof padchar !== 'undefined' ? padchar : '0';
    var pad = new Array(1 + padlen).join(pad_char);
    return (pad + num).slice(-pad.length);
var fu = paddy(14, 5); // 00014
var bar = paddy(2, 4, '#'); // ###2

Third answer

I can’t believe all the complex answers on here… Just use this:

var zerofilled = ('0000'+n).slice(-4);
Spread the love

Related articles

Comments are closed.