Rounding numbers to the nearest 5

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want to be able to round a number like 1107 to the nearest 5, like 1105.

  2. What is the issue? Include screenshots / videos if possible!
    I am not able to do ^^^

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I tried looking at things on Developer Hub and DevForum, though none of them helped.

I am trying to make a leveling up system where when you level up, the xp needed goes up, but I can’t find a way to round it to the nearest 5. Here is the code:

local lvl = stats.Level
local xp = stats.XP

local xpNeeded = 350

while wait(5) do
	
	xp.Value = xp.Value + 250
	
	if xp.Value >= xpNeeded then
		lvl.Value = lvl.Value + 1
		xp.Value = 0
		
		xpNeeded = xpNeeded * math.sqrt(5 * (math.random(1.5, 2)) ) --do some multiplying
		xpNeeded = math.floor(xpNeeded + 0.5) --round to the nearest whole number.
		print(xpNeeded)
	end
end

I’ve been doing some experimenting, and there’s most likely an easier way to do this but maybe you could have logic like…

local function Round(to_round)
    local divided = to_round / 5
    local rounded = 5 * math.floor(divided)
    return rounded
end
print(Round(83))

I believe this does what you want, but let me know otherwise. Hope this helps :slight_smile:

16 Likes

@C_Sharper already did, but this is my method to do it:

local function Round(number, digits)
	return math.floor(number / digits) * digits
end
print(Round(1107, 5))

I tried to keep it as short as possible.

12 Likes

Thank you! I will look into both of your methods.

To have it round to the nearest multiple of 5, rather than to the next lowest one, you would have to add 0.5 since math.floor just cuts off the decimal. For example, 1059 should return 1060 and not 1055. Taking that into account, here’s a better method:

local function round(num, mult)
	return math.floor(num / mult + 0.5) * mult
end

print(round(1059, 5)) --> 1060

Similar to the other examples, it divides the number by 5 to find what you have to multiply 5 by to get it. Then, it rounds that number to the nearest integer. Multiplying it by 5 again will give you the original number rounded to the nearest multiple of 5.

16 Likes

This is unnecessary, as there is no reason for you to think that he needs this in more than one script. Modularization is great for organization, but you shouldn’t try to make people do it when it’s unhelpful.

5 Likes

I might need to use some variables in different functions in the same script, so I can save them in my datastore.