Tom Hammond Tom Hammond - 8 months ago 80
Ruby Question

Round to nearest quarter

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.



While Andrey's solution will work if you are not comfortable with monkey patching a primary ruby class the following will work as well

#x being the value
(x * 4).round / 4.0