HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to output numbers with leading zeros in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
numberswithhowzerosoutputleadingjavascript

Problem

Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.

Solution

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

You'll have to convert the number 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 re-add it.

Code Snippets

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

Context

Stack Overflow Q#2998784, score: 990

Revisions (0)

No revisions yet.