This will just be iLordOfAviation but explained a bit.
math.floor
math.floor takes the mathematical floor of a number - that is, it rounds it down.
4.1 -> 4.0
4.5 -> 4.0
4.9 -> 4.0
5.0 -> 5.0
If we want normal rounding, this isn't quite right, but we can achieve what we want by adding 0.5.
If the number should be rounded down, the decimal part must be less than 0.5. Therefore, adding 0.5 must not push it over to the next whole number.
If the number should be rounded up, the decimal part must be either equal to or greater than 0.5
If greater than 0.5, adding another 0.5 pushes the whole part of the number up by one, with some smaller decimal amount left over. This smaller decimal amount must be less than 0.5.
If equal to 0.5, adding another 0.5 makes the number equal to a whole number. At this point, math.floor doesn't touch it.
Some examples:
4.1 -> 4.6 -> 4.0
4.5 -> 5.0 -> 5.0
4.9 -> 5.4 -> 5.0
5.0 -> 5.5 -> 5.0
The bit with the powers
Typically, the rounding functions you'll find in any sort of library will be concerned with getting decimal numbers to integers. So, if we want to round to a certain number of decimals, we have to get a little creative.
For example, if we multiply a number by 10, round it using the bit above, and then divide by 10, what happens?
- 4.5879 -> 45.879 -> 46.379 -> 46.0 -> 4.6
We end up getting the number rounded to 1 decimal place, which is nearing what we want.
Because we're good programmers, the question becomes "How do we generalise this?". Well let's look at another example to see if we can spot a pattern.
- 8.4453 -> 844.53 -> 845.03 -> 845.0 -> 8.45
Here, we multiplied and divided by 100, and now our number has two decimal places in it. What's the secret?
10^1 = 10 -> 1 decimal place
10^2 = 100 -> 2 decimal places
10^47 -> 47 decimal places
Putting it together
We basically end up with iLordOfAviation's answer.
function round(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult + 0.5) / mult
end
The only slight weirdness left is numDecimalPlaces or 0. This is equivalent to
if numDecimalPlaces ~= nil then
mult = 10^numDecimalPlaces
else
mult = 0
end
3 comments
what does lines 2 and 3 mean?
It's just math to figure out how to round it idk, all you gotta do to round is add that to the top of your script then put a "round(YOUR NUMBER)" where you want it to round
You should not really be posting an answer if you yourself have no idea what the heck it means.