I want to round some numbers to the nearest tenth, using odd tenths only. e.g.
91.15 -> 91.1
91.21 -> 91.3
What's a simple and generic equation for doing this?
This is not rounding to the nearest tenth, but rather rounding to the nearest fifth (two-tenth) with a one-tenth offset. With that in mind, the general equation is:
# Any language where 'round' rounds to the nearest integer
radioStation = round( (original-offset)/interval ) * interval + offset
In Lua:
-- number: the original value to round
-- interval: the distance between desired values
-- offset: an optional shifting of the values
function roundToNearest( number, interval, offset )
offset = offset or 0 -- default value
interval = interval or 1 -- default value
return math.floor( (number-offset)/interval + 0.5 ) * interval + offset
end
for n=1, 2, 0.09 do
local result = roundToNearest(n, 0.2, 0.1)
print(string.format("%.2f : %g", n, result))
end
--> 1.00 : 1.1
--> 1.09 : 1.1
--> 1.18 : 1.1
--> 1.27 : 1.3
--> 1.36 : 1.3
--> 1.45 : 1.5
--> 1.54 : 1.5
--> 1.63 : 1.7
--> 1.72 : 1.7
--> 1.81 : 1.9
--> 1.90 : 1.9
--> 1.99 : 1.9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With