Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby round integer to nearest multiple of 5

Tags:

ruby

I want to take an integer and round it up to the next multiple of 5. Like such:

input:    output:
0    ->   0
2    ->   5
3    ->   5
12   ->   15
21   ->   25
30   ->   30
-2   ->   0
-5   ->   -5
etc.

My function below accounts for the numbers that are divisible by 10, but I have no idea how to do it for the numbers divisible by 5. This is what I have so far;

    def round_to_next_5(n)
      if n % 5 == 0
        return n
      else 
        return n.round(-1)
      end
    end
like image 406
PKP 007 Avatar asked Nov 28 '22 16:11

PKP 007


1 Answers

One could write (16/5.0).ceil * 5 #=> 20 but round-off is a problem for large integers:

(1000000000000001/5.0).ceil * 5
  #=> 1000000000000005   # correct
(10000000000000001/5.0).ceil * 5
  #=> 10000000000000000  # incorrect

For that reason I'd prefer to stick with integer operations.

def round_up(n, increment)
  increment * (( n + increment - 1) / increment)
end

(-10..15).each { |n| puts "%s=>%s" % [n, round_up(n,5)] }

-10=>-10
 -9=> -5  -8=>-5  -7=>-5  -6=>-5  -5=>-5
 -4=>  0  -3=> 0  -2=> 0  -1=> 0   0=> 0
  1=>  5   2=> 5   3=> 5   4=> 5   5=> 5
  6=> 10   7=>10   8=>10   9=>10  10=>10
 11=> 15  12=>15  13=>15  14=>15  15=>15
like image 185
Cary Swoveland Avatar answered Jan 27 '23 16:01

Cary Swoveland