How can I format an integer to a specific length in javascript?

Viewed 122894

I have a number in Javascript, that I know is less than 10000 and also non-negative. I want to display it as a four-digit number, with leading zeroes. Is there anything more elegant than the following?

if(num<10) num="000"+num;
else if(num<100) num="00"+num;
else if(num<1000) num="0"+num;

I want something that is built into Javascript, but I can't seem to find anything.

16 Answers

I don't think there's anything "built" into the JavaScript language for doing this. Here's a simple function that does this:

function FormatNumberLength(num, length) {
    var r = "" + num;
    while (r.length < length) {
        r = "0" + r;
    }
    return r;
}


FormatNumberLength(10000, 5) outputs '10000'
FormatNumberLength(1000, 5)  outputs '01000'
FormatNumberLength(100, 5)   outputs '00100'
FormatNumberLength(10, 5)    outputs '00010'

This might help :

String.prototype.padLeft = function (length, character) { 
     return new Array(length - this.length + 1).join(character || '0') + this; 
}

var num = '12';

alert(num.padLeft(4, '0'));

A funny (but interesting) way to prefix numbers with zeros:

function FormatInteger(num, length) {

    return (num / Math.pow(10, length)).toFixed(length).substr(2);
}

How about something like this:

function prefixZeros(number, maxDigits) 
{  
    var length = maxDigits - number.toString().length;
    if(length <= 0)
        return number;

    var leadingZeros = new Array(length + 1);
    return leadingZeros.join('0') + number.toString();
}
//Call it like prefixZeros(100, 5); //Alerts 00100

You could go crazy with methods like these:

function PadDigits(input, totalDigits) 
{ 
    var result = input;
    if (totalDigits > input.length) 
    { 
        for (i=0; i < (totalDigits - input.length); i++) 
        { 
            result = '0' + result; 
        } 
    } 
    return result;
} 

But it won't make life easier. C# has a method like PadLeft and PadRight in the String class, unfortunately Javascript doesn't have this functionality build-in

I came looking for the answer, but I think this is a better functional approach (ES6):

const formatNumberToString = (num, minChars) => {
  return num.toString().length < minChars
   ? formatNumberToString(`0${num}`, minChars)
   : num.toString()
}
// formatNumberToString(12, 4) // "0012"
// formatNumberToString(12, 5) // "00012"
// formatNumberToString(1, 4) // "0001"
// formatNumberToString(1, 2) // "01"
// formatNumberToString(12, 2) // "12"
// formatNumberToString(12, 1) // "12"

also, this can be implemented just in one line

Latest with ES6 repeat() method:

    const length_required = 5;
    let num = 10;
    num = "0".repeat(length_required - String(num).length) + num;
    console.log(num)
    // output: 00010

    let num = 1000;
    num = "0".repeat(length_required - String(num).length) + num;
    console.log(num)
    // output: 01000

I know this question is kind of old, but for anyone looking for something similar to String formatting on Java or Python, I have these helper methods:

String.format = (...args) => {
    if( args.length == 0 ){
        throw new Error("String format error: You must provide at least one argument");
    }
    const delimiter = "@LIMIT*";
    const format = String(args.shift(1,0)).replace(/(%[0-9]{0,}[sd])/g, delimiter+"$1"+delimiter).split(delimiter); // First element is the format
    if( [...format].filter(el=>el.indexOf("%")>-1).length != args.length ){
        throw new Error("String format error: Arguments must match pattern");
    }
    if( format.length == 1 && args.length == 0 ){
        return String(format);
    }
    let formattedString = "";
    // patterns
    const decimalPattern = /%[0-9]{0,}d/;
    const stringPattern  = /%s/;
    if( format.length == 0 ){
        throw new Error("String format error: Invalid format");
    }
    let value        = null;
    let indexOfParam = 0;
    let currPattern  = null;
    while( args.length > 0 ) {
        currPattern = format[indexOfParam];
        indexOfParam++;
        if( currPattern.indexOf("%")<0 ){
            formattedString+=currPattern;
            continue;
        }
        value = args.shift(0,1);
        if( decimalPattern.test(currPattern) ){
            let numberLength = parseInt(currPattern.replace(/[^0-9]/g,''));
            if( isNaN(numberLength) ){
                numberLength = 0;
            }
            formattedString+=numberToLength(value, numberLength);
        } else if( stringPattern.test(currPattern) ) {
            if( typeof value === 'object' && value.toSource ){
                formattedString+=String(value.toSource());
            } else {
                formattedString+=String(value);
            }
        } else {
            throw new Error("String format error: Unrecognized pattern:"+currPattern);
        }
    }
    return formattedString;
}

const numberToLength = (number, length) => {
    length = parseInt(length);
    number = String(number);
    if( isNaN(length) || isNaN(parseInt(number)) ){
        throw new Error("Invalid number passed");
    }
    while( number.length < length ) {
        number = "0" + number;
    }
    return number;
}
Related