Skip to content
Advertisement

Javascript adding zeros to the beginning of a string (max length 4 chars)

var number = 1310;

should be left alone.

var number = 120;

should be changed to “0120”;

var number = 10;

should be changed to “0010”;

var number = 7;

should be changed to “0007”;

Advertisement

Answer

function pad_with_zeroes(number, length) {

    var my_string = '' + number;
    while (my_string.length < length) {
        my_string = '0' + my_string;
    }

    return my_string;

}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement