Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
Create Function to get Next Number (including decimals)

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
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda