Round to Nearest via Modulus Division: A fun way to snap to a grid of numbers.

posted 2013-Feb-28

Whenever I want to round a number to the nearest something-other-than-integer—such as rounding to the nearest multiple of 20—I tend to use code like this:

function roundToNearest( number, multiple ){
  return Math.round(number/multiple)*multiple;

However, courtesy of Programming in Lua I offer you a different solution that does not invoke a function, but just uses operators:

function roundToNearest( number, multiple ){
  var half = multiple/2;
  return number+half - (number+half) % multiple;

In addition to being geeky fun, this can be over 30% faster in JavaScript.

It’s also about 30% faster in Lua as well:

require 'os'
local c = os.clock
function r1(i,n) return math.floor(i/n+0.5)*n      end
function r2(i,n) local m=n/2; return i+m - (i+m)%n end

local t=c(); for i=1,12345678 do r1(i,20) end; print(c()-t) --> 2.007
local t=c(); for i=1,12345678 do r2(i,20) end; print(c()-t) --> 1.45
02:52PM ET

Using Chrome v56 on Windows, today this is 86% faster than using Math.round()!

net.mind details contact résumé other