I have a grid drawn on a canvas, when the user clicks on the grid, I am drawing a rectangle. I want to always draw the rectangle on top of the grid cell the user is clicking on. So I need to round down to the nearest X, in my case, a multiple of 40.
Some examples ...
121 => 120
125 => 120
139 => 120
159 => 120
160 => 160
So far I have the rounding working using the following...
x = Math.round(x / constants.MAP_CELL_SIZE) * constants.MAP_CELL_SIZE;
This almost handles the rounding, the only thing I am missing is the rounding down to the nearest multiple of 40, which is held in constants.MAP_CELL_SIZE
.
Hopefully this makes sense, and someone can lend a hand ... much appreciated!
Update
It was just as simple as switching from Math.round
to Math.floor
.
I have a grid drawn on a canvas, when the user clicks on the grid, I am drawing a rectangle. I want to always draw the rectangle on top of the grid cell the user is clicking on. So I need to round down to the nearest X, in my case, a multiple of 40.
Some examples ...
121 => 120
125 => 120
139 => 120
159 => 120
160 => 160
So far I have the rounding working using the following...
x = Math.round(x / constants.MAP_CELL_SIZE) * constants.MAP_CELL_SIZE;
This almost handles the rounding, the only thing I am missing is the rounding down to the nearest multiple of 40, which is held in constants.MAP_CELL_SIZE
.
Hopefully this makes sense, and someone can lend a hand ... much appreciated!
Update
It was just as simple as switching from Math.round
to Math.floor
.
-
3
To round down, use
Math.floor()
.Math.round()
goes both ways - up or down whichever is closer. Documentation is here. – Šime Vidas Commented Mar 31, 2013 at 11:27 - Yikes! @ŠimeVidas, it was just that easy ... switching from Math.round to Math.floor did the trick! Thank you! – mattruma Commented Mar 31, 2013 at 11:32
- apologies for misreading your code. assumed it was already Math.floor() – Ejaz Commented Mar 31, 2013 at 11:36
- No problem @Ejay ... I still appreciated the time taken for the suggestion! – mattruma Commented Mar 31, 2013 at 11:39
2 Answers
Reset to default 11To round down, use Math.floor() instead of Math.round(). You can use it like this:
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
See documentation of Math.floor() on MDN.
If you want to truncate the fractional portion of a number, you can use a bitwise operator on it, which will treat the number as a 32 bit integer.
x = x | 0;
Keep in mind this has different behaviour than Math.round()
, which will round correctly with negative numbers.