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

var n = '5';

As a function,

}
var fu = paddy(14, 5); // 00014
var bar = paddy(2, 4, '#'); // ###2
single digit number

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").

I actually had to come up with something like this recently. I figured there had to be a way to do it without using loops.

This is what I came up with.

var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( num < 0 ) {
zeroString = '-' + zeroString;
}

return zeroString+n;
}

Then just use it providing a number to zero pad:

"0050"

If the number is larger than the padding, the number will expand beyond the padding:

"51234"

Decimals are fine too!

"0051.1234"

If you don't mind polluting the global namespace you can add it to Number directly:

var n = Math.abs(this);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( this < 0 ) {
zeroString = '-' + zeroString;
}

return zeroString+n;
}

And if you'd rather have decimals take up space in the padding:

var n = Math.abs(this);
var zeros = Math.max(0, numZeros - n.toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( this < 0 ) {
zeroString = '-' + zeroString;
}

return zeroString+n;
}

Cheers!

XDR came up with a logarithmic variation that seems to perform better.

WARNING: This function fails if num equals zero (e.g. zeropad(0, 2))

var an = Math.abs (num);
var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10);
if (digitCount >= numZeros) {
return num;
}
var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1);
return num < 0 ? '-' + zeroString + an : zeroString + an;
}

Speaking of performance, tomsmeding compared the top 3 answers (4 with the log variation). Guess which one majorly outperformed the other two? :)

Unfortunately, there are a lot of needless complicated suggestions for this problem, typically involving writing your own function to do math or string manipulation or calling a third-party utility. However, there is a standard way of doing this in the base JavaScript library with just one line of code. It might be worth wrapping this one line of code in a function to avoid having to specify parameters that you never want to change like the local name or style.

var amount = 5;

var text = amount.toLocaleString('en-US',
{
style: 'decimal',
minimumIntegerDigits: 3,
useGrouping: false
});

This will produce the value of "005" for text. You can also use the toLocaleString function of Number to pad zeros to the right side of the decimal point.

var amount = 5;

var text = amount.toLocaleString('en-US',
{
style: 'decimal',
minimumFractionDigits: 2,
useGrouping: false
});

This will produce the value of "5.00" for text. Change useGrouping to true to use comma separators for thousands.

Note that using toLocaleString() with locales and options arguments is standardized separately in ECMA-402, not in ECMAScript. As of today, some browsers only implement basic support, i.e. toLocaleString() may ignore any arguments.

Complete Example

In a proposed (stage 3) ES2017 method .padStart() you can simply now do (when implemented/supported):

string.padStart(maxLength, "0"); //max length is the max string length, not max # of fills

Here's a quick function I came up with to do the job. If anyone has a simpler approach, feel free to share!

function zerofill(number, length) {
// Setup
var result = number.toString();
var pad = length - result.length;

result = '0' + result;
}

return result;
}

I really don't know why, but no one did it in the most obvious way. Here it's my implementation.

Function:

/** Pad a number with 0 on the left */
var num = number+"";
while(num.length < digits){
num='0'+num;
}
return num;
}

Prototype:

var num=this+"";
while(num.length < digits){
num='0'+num;
}
return(num);
};

Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.

The power of Math!

y = number of zeroes to pad

{
y = Math.max(y-1,0);
var n = (x / Math.pow(10,y)).toFixed(y);
return n.replace('.','');
}

Don't reinvent the wheel, use underscore string:

jsFiddle

I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.

A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:

console.log(("00000000" + 5).substr(-6));

Generalizing we'll get:

function pad(num, len) { return ("00000000" + num).substr(-len) };

Just an another solution, but I think it's more legible.

function zeroFill(text, size)
{
while (text.length < size){
text = "0" + text;
}

return text;
}

This one is less native, but may be the fastest...

zeroPad = function (num, count) {
var pad = (num + '').length - count;
num = '0' + num;
}
return num;
};

Not that this question needs more answers, but I thought I would add the simple lodash version of this.

Some monkeypatching also works

String.prototype.padLeft = function (n, c) {
if (isNaN(n))
return null;
c = c || "0";
return (new Array(n).join(c).substring(0, this.length-n)) + this;
};

The simplest, most straight-forward solution you will find.

function zerofill(number,length) {
var output = number.toString();
while(output.length < length) {
output = '0' + output;
}
return output;
}

### Tags

javascript   zerofill