'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 1:[1]
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
parseInton an actual number, so it's just+ 1not+ 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).
Solution 2:[2]
I created a function today that you can use for that.
function incrementLeadingZeroNumber(leadingZeroString, amountToIncrement){
var amountOfZerosToAdd = leadingZeroString.length;
var stringToNumber = (+leadingZeroString);
var zerosToAdd = new Array(amountOfZerosToAdd + 1).join( '0' );
var zerosAndNewNumber = zerosToAdd + ( stringToNumber + amountToIncrement )
var amountToSlice = (-1 * amountOfZerosToAdd)
var newString = zerosAndNewNumber.slice(amountToSlice)
return newString
}
//example usage
var incrementedNumber = incrementLeadingZeroNumber('0030', -10)
Solution 3:[3]
Here is a function you can use. min_size is the length of the string, so in your case '0000' min_size is 4. Your databasevalue starts at 0. The function converts the number to a string and checks the length of the string. Then it adds leading zeros till the min_size has been reached. The console.log shows the first following number '0001'. Here it's easy to change the amount of leading zeros.
var min_size = 4;
var start_value = 0;
function leading_zero (num) {
var new_num = num.toString();
for (var i = new_num.length; i < min_size; i++) {
new_num = '0' + new_num;
}
return new_num;
}
console.log(leading_zero(start_value + 1));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Anthony |
| Solution 3 | Thalsan |
