首页 > 解决方案 > 创建函数以获取下一个数字(包括小数)

问题描述

我创建了一个函数,它返回考虑小数的下一个数字,但是当输入数字在小数点后有一个零 (0) 时出现问题。

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

标签: javascript

解决方案


你可以跳过零:

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

一种完全不同的方法,应该可以解决所有提到的问题。我'1'在小数点前添加了字符以避免前导零的问题并存储进位。最后我添加进位并删除这个字符。

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


推荐阅读