# text formatting – How to output numbers with leading zeros in JavaScript

## The Question :

577 people think this question is useful

I can round to x amount of decimal places with math.round but is there a way to round left of the decimal? for example 5 becomes 05 if I specify 2 places

• Not rounding, that’s string formatting.
• I’ve found this wich I guess is far more simple: ("00" + h).slice (-3);
• @PauloBueno ("00" + 1234).slice (-3); gives 234 i.e. discards the most significant figure.
• @DanielEarwicker sure it does but you should adjust to the ammount of digits you are expecting. ("000" + 1234).slice(-4), ("0000" + 12345).slice(-5) and so on…
• If you also want to limit the length of the number you could use this: return (num/Math.pow(10,size)).toFixed(size).split('.')[1];

815 people think this answer is useful

NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart

You’re asking for zero padding? Not really rounding. You’ll have to convert it to a string since numbers don’t make sense with leading zeros. Something like this…

function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}



Or if you know you’d never be using more than X number of zeros this might be better. This assumes you’d never want more than 10 digits.

function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}



If you care about negative numbers you’ll have to strip the “-” and readd it.

282 people think this answer is useful

UPDATE: Small one-liner function using the ES2017 String.prototype.padStart method:

const zeroPad = (num, places) => String(num).padStart(places, '0')



Another ES5 approach:

function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 &amp;&amp; zero)).join("0") + num;
}



245 people think this answer is useful

You could extend the Number object:

Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}



Examples:

(9).pad();  //returns "09"



64 people think this answer is useful
function pad(a,b){return(1e15+a+"").slice(-b)}



function pad(
a, // the number to convert
b // number of resulting characters
){
return (
1e15 + a + // combine with large number
"" // convert to string
}



6 people think this answer is useful
function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}



4 people think this answer is useful

Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:

pad.zeros = new Array(5).join('0');