Round float to the nearest quarter in Ruby

I am working with an external api in a Ruby on Rails application. I need to send floats to this company, but they only accept values ​​such as 1.0 , 1.25 , 1.5 , 1.75 , 2.0 , etc.

I may have a value like 1.34 or 1.80 . Ideally, I need to round them to the nearest 0.25 . What is the best way to do this? if I do 1.34.round(0) , it will give me 1.0 , which is lower than what I need.

Thanks!

+6
source share
2 answers
 (1.27 * 4).round / 4.0 #=> 1.25 

If you intend to use it frequently, it would be ideal for the monkey to pay the Float class to make it easier to use:

 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 
+13
source

While the Andrey solution will work, if you are uncomfortable decapitating the main class of rubies, it will work and

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

All Articles