I've created a function that returns the next number taking into account decimals, but am having an issue when the input number has a zero (0) proceeding the decimal.
const getNextValue = (input) => {
const newNumber = input
.toString()
.replace(/\d+$/, (number) =>
parseInt(number) +1)
return parseFloat(newNumber)
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.3 as it ignores the zeros
You could skip the zeros:
const getNextValue = (input) => {
const newNumber = input
.toString()
.replace(/^\d+$|[1-9]+$/, (number) =>
parseInt(number) + 1);
return parseFloat(newNumber)
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.003
console.log(getNextValue(30)) // returns 31
A completely different approach that should solve all the mentioned issues. I've added the character '1' in front of the decimal places to avoid the problem with leading zeros and to store the carry. At the end I add the carry and remove this character.
const getNextValue = (input) => {
const str = input.toString();
if (!str.includes('.')) return input + 1;
const numbers = str.split('.');
const dec = (+('1' + numbers[1]) + 1).toString();
return parseFloat(`${+numbers[0] + +dec[0] - 1}.${dec.substring(1)}`);
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.003
console.log(getNextValue(3.9)) // returns 4
console.log(getNextValue(3.09)) // returns 3.1
console.log(getNextValue(30)) // returns 31