From rounded to the nearest odd digit

I want to round some numbers to the nearest tenth using only odd tenths. eg.

91.15 -> 91.1
91.21 -> 91.3

What is a simple and general equation for this?

+4
source share
2 answers

This is not rounding to the nearest tenth, but rounding to the nearest fifth (two tenths) with one tenth of an offset. With this 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
+6
source

What about

function roundToOdd(number)
    temp = round(number * 10)
    if number % 2 == 0 then
        if number > temp then
            temp = temp + 1
        else
            temp = temp - 1
        end
    end
    return temp/10
end

Results:

1.10 -> 11.0 -> 11 -> 1.1
1.11 -> 11.1 -> 11 -> 1.1
1.19 -> 11.9 -> 12 -> even -> 11 -> 1.1
1.20 -> 12.0 -> 12 -> even -> 11 -> 1.1
1.21 -> 12.1 -> 12 -> even -> 13 -> 1.3
1.29 -> 12.9 -> 13 -> 1.3
1.36 -> 13.6 -> 14 -> even -> 13 -> 1.3
1.40 -> 14.0 -> 14 -> even -> 13 -> 1.3
1.41 -> 14.1 -> 14 -> even -> 15 -> 1.5
+3
source

All Articles