你怎么能找到最近的nb.5值?
排除.0值,
例,
round(1.0) = 1.5
round(1.99) = 1.5
round(2.0) = 2.5
你可以将0.5
添加到Math.floor()
返回的值:
const round = (number) => Math.floor(number) + 0.5
console.log(round(1.0))
console.log(round(1.99))
console.log(round(2.0))
Math.floor(value) + 0.5
应该这样做。
此外,您应该澄清您的规格......因为最接近的0.5值为1.5和2.5,它们都处于相同的“距离”。
我知道你的例子通过最接近的0.5值来处理这个场景,但这真的是你想要的吗?
function round(num) {
return Math.round((num % 10)) + 0.5
}
console.log(round(1));
console.log(round(1.99));
console.log(round(2));
要获得预期结果,请使用Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc以下选项
let round = (val) => Math.trunc(val) + 0.5
console.log(round(1.99))
console.log(round(1))
console.log(round(2))