Home

Round to the nearest 0.5 in Ruby

A cool and quick trick to round floats to the nearest 0.5 in 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
end

end

Then, you can simply use:

3.74.round_to_half
# => 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:

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

Let's Connect

Keep Reading

How To Reverse a Ruby Hash

It's nice and easy to reverse a ruby array. See how to easily convert a hash as well.

Oct 18, 2014

Check if a File is Binary or Text in Ruby

Here's a cool little trick to determining if a file is text or binary in Ruby just by using the path to that file.

Dec 15, 2014

Use Slack For Rails Error Notification

Post a message to one of your Slack channels when your Rails app encounters a 500 error.

Dec 22, 2015