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

The simplest way I can think of is this:

("000" + num).slice(-4)

A padded number is a string.
When you add a number to a string, it is converted to a string.
Strings has the method slice, that retuns a fixed length piece of the string.
If length is negative the returned string is sliced from the end of the string.

to test:

var num=12;
console.log(("000" + num).slice(-4)); // Will show "0012"

Of cause this only works for positive integers of up to 4 digits. A slightly more complex solution, will handle positive integers:

'0'.repeat( Math.max(4 - num.toString().length, 0)) + num

Create a string by repeat adding zeros, as long as the number of digits (length of string) is less than 4 Add the number, that is then converted to a string also.

Edit: from now on you should probably use this function:

String(num).padStart(4,'0')

It still doesn't handle negative numbers...


Since ES2017 padding to a minimum length can be done simply with String.prototype.padStart and String.prototype.padEnd:

let number = 3
let string = number.toString().padStart(3, '0')
console.log(string) // "003"

Or if only the whole part of a float should be a fixed length:

let number = 3.141
let array = number.toString().split('.')
array[0] = array[0].padStart(3, '0')
let string = array.join('.')
console.log(string) // "003.141"

Neither of these simple uses handle sign, only showing a fraction part when number is not an integer, or other scenarios - so here is a simple example formatting function without options:

function format (number) {
    let [ integer, fraction = '' ] = number.toString().split(".")
    let sign = ''
    if (integer.startsWith('-')) {
        integer = integer.slice(1)
        sign = '-'
    }
    integer = integer.padStart(3, "0")
    if (fraction) {
        fraction = "." + fraction.padEnd(6, "0")
    }
    let string = sign + integer + fraction
    return string
}

console.log(format(3)) // "003"
console.log(format(-3)) // "-003"
console.log(format(4096)) // "4096"
console.log(format(-3.141)) // "-003.141000"

Although notably this will not handle things that are not numbers, or numbers that toString into scientific notation.


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);
}