我想要使用 javascript 自定义 ceil 和 floor。例如:如果特定的浮点变量为 10.1,那么我需要结果为 10(floor),如果该值大于 10.1,那么我需要将其设为 11(ceil)。这里 10 是可变的。谁能给我一个解决方案?
最佳答案
最好用数学而不是加小数。减去整数,检查余数,如果大于 .1 则更新整数并返回。
function customRound (num) {
let wn = Math.floor(num)
let adj = num - wn > .1 ? 1 : 0
return wn + adj
}
console.log('10.1', customRound(10.1))
console.log('10.11', customRound(10.11))
console.log('10.01', customRound(10.1))
console.log('10.100000000001', customRound(10.100000000001))
关于javascript - 如何获得给定变量的自定义 ceil 和 floor 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56478167/