Augustin Riedinger Augustin Riedinger - 7 months ago 35
Ruby Question

Integer division with rounding

I need to do integer division. I expect the following to return

2
instead of the actual
1
:

187 / 100 # => 1


This:

(187.to_f / 100).round # => 2


will work, but does't seem elegant as a solution. Isn't there an integer-only operator that does
187 / 100 = 2
?

pjs pjs
Answer

You can do it while remaining in the integer world as follows:

def round_div(x,y)
  (x + y / 2) / y
end

If you prefer, you could monkey-patch Fixnum with a variant of this:

class Fixnum
  def round_div(divisor)
    (self + divisor / 2) / divisor
  end
end

187.round_div(100)    # => 2