Creé una función que devuelve el siguiente número teniendo en cuenta los decimales, pero tengo un problema cuando el número de entrada tiene un cero (0) antes del 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 zerosPodrías saltarte los ceros:
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 Un enfoque completamente diferente que debería resolver todos los problemas mencionados. Agregué el carácter '1' delante de los lugares decimales para evitar el problema con los ceros a la izquierda y para almacenar el acarreo. Al final agrego el carry y elimino este personaje.
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