Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do you make a function that rounds?

Asked by 5 years ago

All I see is math.floor and math.ceil, what would you do to round to the nearest tenths/hundredths etc

2 answers

Log in to vote
1
Answered by
chomboghai 2044 Moderation Voter Community Moderator
5 years ago

Try taking a look at this page.

It has very useful information about rounding functions in Lua.

Ad
Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

If we look at a normal rounding function it goes like this:

function round(num)
return math.floor(num+0.5)
end
print(round(1.45))

However we want to round it to a higher place. Notice how in numbers like 14.5 we round it and it becomes 15. We want that, but with 1.45, to become 1.5. This is really simple actually, all we do is multiply it by how many places we want it to go when we math.floor it, then divide it afterwards. 10th place Example:

function round(num)
return math.floor((num*10)+0.5)/10
end
print(round(1.45))

100th place Example:

function round(num)
return math.floor((num*100)+0.5)/100
end
print(round(1.457))

If you need any more help just ask! :D

0
Can't accept both answers sadly, thank you for the example, but I accepted the other dudes due to making me work it out myself which in return helps me learn better. masterblokz 58 — 5y

Answer this question