如何在Javascript中始终向下舍入到最接近的X?

mat*_*uma 1 javascript

我在画布上绘制了一个网格,当用户点击网格时,我正在绘制一个矩形.我想总是在用户点击的网格单元格顶部绘制矩形.所以我需要向下舍入到最接近的X,在我的情况下,是40的倍数.

一些例子 ...

121 => 120
125 => 120
139 => 120
159 => 120
160 => 160
Run Code Online (Sandbox Code Playgroud)

到目前为止,我使用以下方法进行舍入工作...

x = Math.round(x / constants.MAP_CELL_SIZE) * constants.MAP_CELL_SIZE;
Run Code Online (Sandbox Code Playgroud)

几乎处理了舍入,我唯一缺少的是向下舍入到最接近的40的倍数,这是保持在constants.MAP_CELL_SIZE.

希望这是有道理的,有人可以伸出援助之手......非常感谢!


更新

它就像切换Math.round到一样简单Math.floor.

Mif*_*eet 8

要向下舍入,请使用Math.floor()而不是Math.round().你可以像这样使用它:

var customFloor = function(value, roundTo) {
    return Math.floor(value / roundTo) * roundTo;
}

customFloor(121, constants.MAP_CELL_SIZE); // => 120
customFloor(159, constants.MAP_CELL_SIZE); // => 120
customFloor(160, constants.MAP_CELL_SIZE); // => 160
Run Code Online (Sandbox Code Playgroud)

请参阅MDN上的Math.floor()文档.