How do I round a float value to the nearest multiple of \"n\"?
For instance, rounding 21.673 to the nearest multiple of 8 should result in 24.
And, rounding 21.6
It is easy
Math.round(value / n) * n
There's another one, slightly shorter, slightly faster:
const nearrestMultipleOfN = (N,n) => n*(N/n+0.5|0);
It seems to deliver what's expected:
const nearrestMultipleOfN = (N,n) => n*(N/n+0.5|0);
console.log(nearrestMultipleOfN(21.673,8));
console.log(nearrestMultipleOfN(21.673,4));
.as-console-wrapper{min-height:100%}
If you find yourself looking for the greatest integer divisible by n
that does not exceed N
(i.e. return 6, divisible by 3, when given 8), you might go, like:
const nearrestMultipleOfN = (N,n) => n*(N/n|0);