Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I round a number to the nearest multiple of 4?

This is one of my first steps to creating a 4x4 grid. Say I click on a position at Vector3.new(3, 6, 13). I want to round that position to my 4x4 grid so I would probably do this??

function round(pos)
	pos = Vector3.new(pos.X%4, pos.Y%4, pos.Z%4)
return pos
end

-- now round(Vector3.new(3, 6, 13) should round to Vector3.new(4, 8, 12)????

1 answer

✓ Accepted answer

I have this function someone told me to round numbers. This will only round downward if I remember correctly.

function round(num, numToRound)
	return tonumber(math.floor(num / numToRound) * numToRound)
end

local X = round(3, 4)
local Y = round(6, 4)
local Z = round(13, 4)

print('The position is '..X..', '..Y..', '..Z)

It should print "The position is 0, 4, 12".

3 comments

0

will this work even if decimals are in the numbers? this is my last question.

0

Yes. The place it defines the number to round is in math.floor. That removes decimals.

0

great thanks

This discussion is preserved as it was. New answers, comments, and votes are closed.