Snap number to certain interval

So like if I want a grid placement system and the interval is 2 and x is 2.34 then it would turn into 2 and if it were 3.19 then it would turn into 4
Or if i want to have it rotate and have it anti exploit which is use remoteevent then i needa make it snap to 90 degrees so like if it were like 84.284 then it woukd snap to 90 and if it were 32.124 then it would snap to 0 and if it were 127.2 then it would snap to 90 and if it were 150.3 then it would snap to 180

1 Like

Here’s a rounding function that lets you round to the nearest to, where to is any number:

function round(n, to)
    return math.floor(n/to + 0.5) * to
end

You can round to nearest 10 like this: round(13.45, 10) => 10, to nearest 2 like this: round(15.34, 2) => 16, etc. You can round to any number, doesn’t have to be a whole number or >= 1.

2 Likes

Ok thanks and how do I put it in a modulescript so I can use the function anywhere

You can do it like this:

local module = {}
function module.round(n, to)
      return math.floor(n/to + 0.5) * to
end
return module

Then you can access it like so:

local module = require(game.ReplicatedStorage.Module) -- Assuming it's in rep storage and is called Module

and access the function like so:

module.round() -- put parameters it requires

p.s. sorry about the indenting if it bothers you, i did this directly in devforum

3 Likes

Messiah!!!

1 Like