Rounding Numbers in Ruby
This article will show you how to round numbers up and down using Ruby.
Published on:August 5, 2013
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:
You can also round to a decimal by passing the number of decimals you wish to keep as an argument. For example:
1.2591.round # returns 1 1.6345.round # returns 2
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
What if we want to round down to a specific decimal? We can simply pass in the number of decimals as a parameter:
1.954.floor(2) # returns 1.95
Similarly, we can round up using the .ceil method:
1.323.ceil # returns 2 1.323.ceil(2) #returns 1.33
Great! That's it for rounding numbers. Thanks for reading!