javascript - 创建函数以获取下一个数字(包括小数)
问题描述
我创建了一个函数,它返回考虑小数的下一个数字,但是当输入数字在小数点后有一个零 (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
解决方案
你可以跳过零:
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
推荐阅读
- python - Geo Django 3.2 django.db.utils.OperationalError:没有这样的功能:lwgeom_version
- unit-testing - 如何为配置类实现junit测试用例?
- java - 是否可以将 GLSL 着色器添加到 android Canvas?
- sql-server - SQL:计算两个日期之间的时间段是否等于或小于 3 个月
- three.js - 在 Aframe 中,我如何做到这一点,以便物体在与它们碰撞时可以阻止我进一步进入它们?
- reactjs - 错误:[Home] 不是
零件。的所有子组件 必须是 或者 - python - 从 mac 上的多个位置删除 python
- r - 用 R 计算向量中的重复元素(可变长度)
- hibernate - 我在作为对象的方法上创建了一个查询,但我不知道如何让它返回对象
- javascript - 单击菜单项后,JS汉堡菜单不折叠