首页 > 解决方案 > 即使数字等于最接近的 2,如何将数字四舍五入为 2

问题描述

我想将任何数字向下舍入 2,但如果该数字完全可被 2 整除,也可以将其向下舍入 2。

例如,1 向下舍入为 0,1.5 向下舍入为 0,2 向下舍入为 0。

但如果该数字大于 2 且不等于 2,则将其四舍五入为 2 而不是 0。

到目前为止,我的代码是Math.floor(x / 2) * 2,但这会返回 2 而不是 0。我怎样才能对其进行编码以便它也舍入精确的除法?

标签: javascript

解决方案


您自己的方法几乎就在那里。它只对正好是 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))


推荐阅读