Tom Hammond Tom Hammond - 1 year ago 82
Ruby Question

Round float to the nearest quarter in Ruby

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.


Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download