Rounding to the nearest multiple of a number
The standard-ish way to round to the nearest multiple in javascript is a function like this:
const round = (number, step) => {
return Math.round(number / step) * step;
};
This works great. There’s absolutely no need to modify it and you should probably just stop reading here. But there’s another neat method that uses the modulus operator.
const round = (number, step) => {
const half = step / 2;
return number + half - ((number + half) % step);
};
The problem with this method is that it doesn’t handle negative numbers correctly. You’ll get round(-1,1) === 0
when it should be -1
.
You can fix it by inverting the step when dealing with negative numbers:
const round = (number, step) => {
if (number < 0) step = step * -1;
const half = step / 2;
return number + half - ((number + half) % step);
};
There are reports this method is quite a bit faster in javascript, but my tests have shown inconclusive results, so probably don’t bother changing anything.