Round float to the nearest quarter in Ruby

floating-point, ruby, ruby-on-rails

Solution

(1.27 * 4).round / 4.0
#=> 1.25

If you're going to use it often, it would make perfect sense to monkey patch the `Float` class, to make the usage simpler:

class Float
  def round_to_quarter
    (self * 4).round / 4.0
  end
end
1.27.round_to_quarter
#=> 1.25
1.52.round_to_quarter
#=> 1.5
1.80.round_to_quarter
#=> 1.75
1.88.round_to_quarter
#=> 2.0

Problem

I'm working with an external api in a Ruby on Rails app. I need to send in floats to this company but they only accept values like `1.0`, `1.25`, `1.5`, `1.75`, `2.0`, etc. I may have a value like `1.34` or `1.80`. I ideally need to round them to the nearest `0.25`. What's the best way to accomplish this? if I do `1.34.round(0)` it'll give me `1.0` which is lower than I need. Thanks!

Original source