Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!