I know you can round up/down to the nearest whole number, but is there a way to round to the nearest decimal value?
i.e. Is there a way to round the number 3.48888888888888888888 to 3.5 instead of rounding the entire number down to 3?
Divide by the interval, round, multiply by the interval. If you take 34 and divide it by 10 and round that, then multiply by 10, you get 30.
function round(x,near) return math.floor(x/near+.5)*near end
What you can do is change the decimal power of the number, round it and then set the decimal power back.
function roundToNearest(number, decimals) local decimalPower = math.pow(10, decimals) local powered = number * decimalPower -- We power the number up so we can round the decimal part and not the whole number local round = math.floor(powered + 0.5) -- We add 0.5 so it rounds, instead of flooring or ceiling local final = round / decimalPower -- Bringing back the power return final end
The decimals
argument is how many decimal points you want to preserve. You can use negative numbers to round the whole part, 0 to return only the whole part and positive numbers to round the decimals.
Hope this helped.