Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thanks!

like image 712
Tom Hammond Avatar asked Oct 17 '16 15:10

Tom Hammond


1 Answers

(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
like image 184
Andrey Deineko Avatar answered Oct 06 '22 00:10

Andrey Deineko