舍入到最接近的0.5,不是0.0

问题描述 投票:-1回答:4

你怎么能找到最近的nb.5值?

排除.0值,

例,

round(1.0) = 1.5
round(1.99) = 1.5
round(2.0) = 2.5
javascript math
4个回答
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))

4
投票

Math.floor(value) + 0.5应该这样做。

此外,您应该澄清您的规格......因为最接近的0.5值为1.5和2.5,它们都处于相同的“距离”。

我知道你的例子通过最接近的0.5值来处理这个场景,但这真的是你想要的吗?


0
投票

function round(num) {
    return Math.round((num % 10)) + 0.5
}

console.log(round(1));
console.log(round(1.99));
console.log(round(2));

0
投票

要获得预期结果,请使用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))
© www.soinside.com 2019 - 2024. All rights reserved.