在JavaScript中截断到最接近的50



我可以使用什么JavaScript公式将数字截断到最接近的50。实例我想要498>450

我试过

Math.round (498, 50 )

而且Math.ceil(498, 50)

但我没有得到。请帮助

这可能是术语的混合,混合了诸如";最近的";以及";截断";,这两个都不太描述了示例演示的内容。

您给出的示例总是向下四舍五入,而不是向上四舍五舍五入到最接近的自定义值(在本例中为50(。要做到这一点,您可以减去% 50的结果。例如:

const val = 498;
console.log(val - val % 50);

甚至使其成为可重复使用的功能:

const Nearest = (val, num) => val - val % num;
console.log(Nearest(498, 50));

除以50,进行运算,乘以50。

console.log(Math.floor(498 / 50) * 50);
console.log(Math.ceil(498 / 50) * 50);
console.log(Math.round(498 / 50) * 50);
console.log(Math.trunc(498 / 50) * 50);

将数字除以50,取该数字的上限,然后乘以50。

Math.ceil(value / 50) * 50;

简要说明:truncate对Javascript中的数字有另一种意义:MDN 上的Math.trunc

编辑:

如果您想要除ceil之外的其他舍入语义,您当然可以使用floor(始终为50的最低倍数(:

Math.floor(451 / 50) * 50; // => 450

除以倍数并取整,然后乘以倍数。如果你想要下限,你可以用地板而不是圆形。如果你想要上限,你可以用ceil而不是圆形。看看这些例子:

let x = 498;
let y = Math.round(498/50)*50;
console.log(y);
y = Math.floor(498/50)*50;
console.log(y);
y = Math.ceil(498/50)*50;
console.log(y);

要想做什么,Remainder运算符是您最好的朋友。这将为您提供该数字除以nearest数字后剩下的任何内容。

如果你的目标是总是向下取整,那么下面的函数就会起作用。只需取您的原始号码,找到剩余号码,然后删除剩余号码:

function roundDownToNearest(num, nearest){
return num - (num % nearest);
}
console.log(roundDownToNearest(498, 50))

如果你总是想向上取整,你就向下取整,然后加上nearest金额:

function roundUpToNearest(num, nearest){
return num - (num % nearest) + nearest;
}
console.log(roundUpToNearest(498, 50))

如果你想获得两者中最接近的一个,你可以做以下事情。找到你的余数,然后看看它是大于还是小于你的nearest值的一半。如果较大,请四舍五入。如果少于,则四舍五入。

function roundToNearest(num, nearest){
if(num % nearest > nearest / 2){
return roundUpToNearest(num, nearest);
} else {
return roundDownToNearest(num, nearest);
}
}
console.log(roundToNearest(498, 50))
console.log(roundToNearest(458, 50))

最新更新