javascript - 即使数字等于最接近的 2,如何将数字四舍五入为 2
问题描述
我想将任何数字向下舍入 2,但如果该数字完全可被 2 整除,也可以将其向下舍入 2。
例如,1 向下舍入为 0,1.5 向下舍入为 0,2 向下舍入为 0。
但如果该数字大于 2 且不等于 2,则将其四舍五入为 2 而不是 0。
到目前为止,我的代码是Math.floor(x / 2) * 2
,但这会返回 2 而不是 0。我怎样才能对其进行编码以便它也舍入精确的除法?
解决方案
您自己的方法几乎就在那里。它只对正好是 2 的倍数的数字失败。您可以通过这种方式专门处理这些数字,因此使该函数适用于所有正数:
function round_down_to_nearest_2(num) {
const rounded_val = Math.floor(num / 2) * 2;
return rounded_val === num ? rounded_val - 2 : rounded_val;
}
console.log(round_down_to_nearest_2(1))
console.log(round_down_to_nearest_2(1.5))
console.log(round_down_to_nearest_2(2))
console.log(round_down_to_nearest_2(4))
console.log(round_down_to_nearest_2(4.0001))
console.log(round_down_to_nearest_2(123.0001))
推荐阅读
- javascript - NodeJS & React w/ DevExpress - 导入变量抛出语法错误
- mongodb - 如果参数值不是数组,如何计算大小
- python - 在情节中从x轴中删除重复的年份
- r - 在 R 中不使用密钥访问 S3 存储桶
- vue.js - 观看从父母到孩子的道具变化
- javascript - SVG 动画(ICO 到 SVG 文件)
- django-models - 如何在 Django 中设计有向图模型?
- react-native - 字体大小在反应原生的不同设备中缩小(不响应)
- elasticsearch - 如何使用 elasticsearch 获取嵌套字段的所有值?
- arrays - Vue 在两个 for 循环中调用 Api