A better Ruby implementation of round decimal to nearest 0.5 A better Ruby implementation of round decimal to nearest 0.5 ruby ruby

A better Ruby implementation of round decimal to nearest 0.5


class Float  def round_point5    (self * 2).round / 2.0  endend

A classic problem: this means you're doing integer rounding with a different radix. You can replace '2' with any other number.


Multiply the number by two.

round to whole number.

Divide by two.

(x * 2.0).round / 2.0

In a generalized form, you multiply by the number of notches you want per whole number (say round to .2 is five notches per whole value). Then round; then divide by the same value.

(x * notches).round / notches


You can accomplish this with a modulo operator too.

(x + (0.05 - (x % 0.05))).round(2)

If x = 1234.56, this will return 1234.6

I stumbled upon this answer because I am writing a Ruby-based calculator and it used Ruby's Money library to do all the financial calculations. Ruby Money objects do not have the same rounding functions that an Integer or Float does, but they can return the remainder (e.g. modulo, %).

Hence, using Ruby Money you can round a Money object to the nearest $25 with the following:

x + (Money.new(2500) - (x % Money.new(2500)))

Here, if x = $1234.45 (<#Money fractional:123445 currency:USD>), then it will return $1250.00 (#

NOTE: There's no need to round with Ruby Money objects since that library takes care of it for you!