Apologies if I'm asking a simple question as existing answers couldn't provide me with a solution. I'd like to know what is the simplest way to snap (floor ceil or round) a value to the closest unit to that value given a grid size? I don't much care about the snapping pattern as long as it's consistent, but it must work with fractional grid units as well as for negative numbers.
Some examples, if the grid size is 0.25 and a value is passed through the snapping function:
0.1 = 0
0.5 = 0.5
-0.2 = -0.25
0.9 = 1
-0.45 = -0.5
3.125 = 3
-42.675 = -42.75
99.765 = 100
If my range was guaranteed to be between 0 and 1 (or 0 and -1) I could probably use const x_snapped = Math.round(x / grid) * grid. This would however stop working if x and / or grid are greater than 1 or lower than -1, I think only whole numbers would be returned then.
const x_grid = Math.round(x / grid) * grid
This will in fact work with all values of x: For some reason I was convinced the result would get rounded to an integer past 1 and decimals would get discarded. Sorry for my silly mistake, but at least this provides an useful answer for others running into the same question and finding this.