在 JS 中将数字(向上或向下)舍入到最接近的 5

将数字四舍五入到最接近的 5

Round a Number (up or down) to the Nearest 5 in JS

要将数字四舍五入到最接近的 5,请调用该Math.round()函数,将数字除以5并将结果乘以传递给它5Math.round
函数接受一个数字,将其四舍五入为最接近的整数并返回结果。

索引.js
function roundNearest5(num) { return Math.round(num / 5) * 5; } console.log(roundNearest5(12)); // 👉️ 10 console.log(roundNearest5(13)); // 👉️ 15 console.log(roundNearest5(-13)); // 👉️ -15 console.log(roundNearest5(-12)); // 👉️ -10 console.log(roundNearest5(32.4)); // 👉️ 30 console.log(roundNearest5(32.5)); // 👉️ 35

我们使用
Math.round
函数将数字四舍五入为最接近的整数。

以下是使用该Math.round功能的一些示例。

索引.js
console.log(Math.round(4.49)); // 👉️ 4 console.log(Math.round(4.5)); // 👉️ 5 console.log(Math.round(40)); // 👉️ 40 console.log(Math.round(-44.5)); // 👉️ -44 console.log(Math.round(-44.51)); // 👉️ -45 console.log(Math.round(null)); // 👉️ 0
Math.round使用值调用该函数时null ,它返回0

我们就是这样一步步解决的。

索引.js
console.log(12 / 5); // 👉️ 2.4 console.log(13 / 5); // 👉️ 2.6 console.log(Math.round(12 / 5)); // 👉️ 2 console.log(Math.round(13 / 5)); // 👉️ 3 console.log(Math.round(12 / 5) * 5); // 👉️ 10 console.log(Math.round(13 / 5) * 5); // 👉️ 15

这是一个两步过程:

  1. 将数字除以5并将结果四舍五入到最接近的整数。
  2. 将结果乘以5得到四舍五入到最接近的数字5

Math.round功能为我们处理所有繁重的工作。