The goal of this article is to demonstrate how to round numbers up or down in Ruby. The examples below can be run in a regular ruby prompt (you can start one by typing 'irb' from the terminal.) These examples work on Ruby on Rails models, views, or controllers as well.

The first thing we will go over is rounding to the nearest decimal place. This is accomplished using the round method. To round to a whole number, simply call round without any arguments. For example:


 1.2591.round # returns 1
 1.6345.round # returns 2
You can also round to a decimal by passing the number of decimals you wish to keep as an argument. For example:

 1.259.round(2) # returns 1.26
 1.312.round(1) # returns 1.3

Great! However, what if we always need to round up or down? Ruby also provides a number of functions to accomplish this.

To round down we use the floor function. The floor function. See the following example:


1.954.floor # returns 1

One thing you will notice here is that the floor function doesn't take any arguments. How do we round down to the nearest decimal then? Well, luckily, we can add a method to Ruby's Float class that will allow this. The example code below creates a method called floor2 on the float class. This enables you to do something like 1.234.floor2(2) similar to the examples for float.


class Float
  def floor2(exp = 0)
   multiplier = 10 ** exp
   ((self * multiplier).floor).to_f/multiplier.to_f
  end
end

1.888.floor2(2) # returns 1.88
1.888.floor2(1) # returns 1.8

Excellent! How about always rounding up a number? Similarly to rounding down, we can round up using the ceil function. However, once again we face the issue of ceil not taking any arguments. We can solve this by creating our own ceil function. See the code listed below:



class Float
  def ceil2(exp = 0)
   multiplier = 10 ** exp
   ((self * multiplier).ceil).to_f/multiplier.to_f
  end
end

puts 1.884.ceil2(1) # returns 1.9
puts 1.884.ceil2(2) # returns 1.89
Great! Well that's it for rounding numbers. Please feel free to leave any feedback in the comments below.