Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 451
Brownman Revival Avatar asked Oct 21 '25 04:10

Brownman Revival


2 Answers

// 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"
like image 96
Fabrizio Calderan Avatar answered Oct 23 '25 17:10

Fabrizio Calderan


Numbers don't have leading zeroes; that's a string thing.

If the value you're getting from the database is a string, you'll need to do this:

  1. Get its length

  2. Use parseInt(theString, 10) to parse it in base 10 (on some engines, a leading zero makes it think it should use base 8)

  3. Add one to it (you never need to use parseInt on an actual number, so it's just + 1 not + parseInt(1))

  4. Convert that into a string

  5. Add zeroes to the beginning of the string in a loop until it's as long as the original

There's no built-in padding function that will do #5 for you, you either have to write one or do one of the hacks like theString = "00000000000000000000000".substr(theString.length - desiredLength) + theString (being sure that initial string has enough zeroes to cover what you want to cover).

like image 36
T.J. Crowder Avatar answered Oct 23 '25 17:10

T.J. Crowder