Search code examples
javascripthtml

Increment a number without getting rid of leading zeroes


I am getting a value from database and I am reusing it as a number. This number has leading zeroes and it is limited to only 4 digits, meaning to say the format is 0001 or 0010 or 0100 or 1000. I am starting the count from zero when I add 1 to this number the leading zeroes are gone the way I add is for example

var databasevalue = 0000;
var incrementvalue = parseInt(databasevalue) + parseInt(1); 

Solution

  • // I suppose databasevalue is a string
    var databasevalue = "0125"; 
    
    // coerce the previous variable as a number and add 1
    var incrementvalue = (+databasevalue) + 1;
    
    // insert leading zeroes with a negative slice
    incrementvalue = ("0000" + incrementvalue).slice(-4); // -> result: "0126"