How to round numbers

If I generated a number between 1 and 100 and got 15 or 20 then it would stay like that but if i got 13,14,12,etc it would be 10

1 Like

Probably sometihng like this

math.round(number / 10) * 10

Edit: Wait do you want 15 -20 to round to 20 or just the numbers under?

Edit 2: I think this should be what you can do from double reading it

if number % 10 < 5 then
	number = math.round(number / 10) * 10
end
1 Like

math.ceil will round up every time
math.floor will round down every time
math.round will round normally like how 5 goes up but 4 goes down

if the number is 15 or 20 or 30 then it stays the same, if its 12 it changes to 10

Try out what I had placed in my edit, it’ll use the modulo operator (basicalyl gets the remainder), and if it returns 5 or more, ignore, otherwise it’ll round,

why are you doing (number / 10) * 10

So you want it to round to every 5?

I would do this simple approach

number = math.random(1,100)
while number % 5 ~= 0 do
    number++ -- or minus to round down
end

13 = 10

24 = 20

31 = 30

15 = 15

20 = 20

Here’s a rounding function I threw together. I’m not sure exactly how to do what you want, but this should work as a nice foundation:

local function Round(num)
    return math.floor(num + 0.5)
end

The reason why is because math.round only works with decimal numbers, you can’t round whole numbers like that,

What it does is first divive number by 10, so if iit was 14 it would be 1.4, then it rounds it, so it would be 1, then multiplies back by 10, so the end result would be 10.

Although I think you can make do using math.floor instead

ok in that case I believe my script would work just replace
number++ with number–

and what does number % 10 < 5 mean

% is the modulo operator, it acts as a division but returns the remainder.

Say you did

print(3 % 2)

It would print 1 because 3 divided by 2 is 1 remainder 1. Basically, it’s getting the remainder of nubmer divided by 10, and checking if the remainder is under 5, if it is, then we know we need to round down

% or modulo will divide and then the answer will be the remainder of the division

just calculated and it returns 1.5

The code I gave works fine for me, did you remember to put in that if statement to change the number? number is the randomized number you obtained, so

local number = math.random(1, 100)

if number % 10 < 5 then
   number = math.floor(number / 10) * 10
end
print(number)

As an example, I used math.floor this time since it wont really matter in this case so long as it rounds down

Edit: Oh he was referring to my print(3 % 2) example, did you accidentally use / instead of %?

3 % 2 is 1 not 1.5 so idk what you mean

image

that is dividing that isn’t modulo at all

/ = divid
% = modulo

you know math right?