将数字四舍五入到最接近的 5
Round a Number (up or down) to the Nearest 5 in JS
要将数字四舍五入到最接近的 5,请调用该Math.round()
函数,将数字除以5
并将结果乘以传递给它5
。该Math.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
这是一个两步过程:
- 将数字除以
5
并将结果四舍五入到最接近的整数。 - 将结果乘以
5
得到四舍五入到最接近的数字5
。
该Math.round
功能为我们处理所有繁重的工作。