Round to the nearest 0.5 in Ruby

Nov 01, 2014 Ruby

To round a number to the nearest 0.5 in most programming languages, you multiply the number by 2, round it, then divide the result by 2.

In Ruby, this looks like this:

(x * 2.0).round / 2.0

If you are going to use it a lot, you can add it to the Float class:

class Float

  def round_to_half
    (self * 2.0).round / 2.0


Then, you can simply use:

# => 3.5

Just make sure you use a float and not an integer, as that method won't be available in another class (unless you make it available). For example:

# => undefined method `round_to_half' for 2:Fixnum

Did you learn something or find this article interesting?

If so, why not