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);
// 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"
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:
Get its length
Use parseInt(theString, 10) to parse it in base 10 (on some engines, a leading zero makes it think it should use base 8)
Add one to it (you never need to use parseInt on an actual number, so it's just + 1 not + parseInt(1))
Convert that into a string
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With