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


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

Let's Connect

Keep Reading

Dynamic Attributes on Instances in Ruby

Although it's not usually the right choice, when you want to create individual attribute behavior on instances, Ruby has your back.

May 01, 2018

A Quicker Way to Compare Multiple Equals Operators in Ruby

When you attempt to write several predictable comparisons in one statement, it gets ugly fast. Here are some methods for cleaning it up.

Apr 20, 2015

Identify Liquid Bottlenecks by Profile Jekyll Builds

It's easy to let Liquid templates get away and bog down build times. Here's a quick way to find out which templates are the culprits.

Aug 19, 2018