Hi! Using a number value, I need to round it’s value to the nearest whole number since I use decimals for a multiplication sequence. How could I do this so that, for example, a value of 10.001010894124312 becomes just 10.
local function round(n)
return math.floor(n + 0.5)
end
Floor just drops the decimal (rounds down), so any number with a decimal < 0.5 would not get to the next integer (rounding down), where >= 0.5 would (and thus round down to the next highest).
This function rounds up at 0.5, if you have a preference to round down if at 0.5, you have to use math.ceil and subtract 0.5 instead.
It worked! Thank you so much.
Here’s a quicker way of rounding in cases where performance is the must:
(n + 0.5) - (n + 0.5) % 1
Add 0.5 to n
, putting it over the bar if it’s already >0.5, then subtract the “remainder” decimal from it.
Here’s How to round a number with good performance
(Edit: I did not know that math.round() was a thing when I posted this, as it was not listed in the developer reference api at the time, but I learned that my method performs better than math.round)
local x = --whatever x is
x = x+0.5
x = math.floor(x)
print(x)
The simplest way to round would be by using math.round (displayed below).
local function round(number, decimalPlaces)
return math.round(number * 10^decimalPlaces) * 10^-decimalPlaces
end
-- Input/Output Examples
5.55555, 4 --> 5.5556
10.9995, 3 --> 11
0.5, 0 --> 1
This is the proper way. Thanks. @CheekySquid should choose this as correct answer. The other methods were also ok, but this fits at most.
math.round()
now exists