We can use Ruby to round a number to the nearest integer by using the round method. The round Ruby method rounds a number to the nearest integer.
4.653.round
The above code would return 5, as it would round the number 4.653
to the nearest integer, 5.
Note that we can also pass the round method an integer parameter that will be the number of decimal places that we want to round the number to.
4.653.round(2)
Let’s see the output of both of these simple examples.
num1 = 4.653.round
num2 = 4.653.round(2)
puts num1
puts num2
#Output:
5
4.65
One calculation that is very easy to perform in Ruby is rounding a number.
We can round a number easily with the Ruby round method.
Below are some examples of how to use round in Ruby to round a bunch of different numbers.
puts 5.2.round
puts 10.867986.round(3)
puts 43.5.round(1)
puts -12.3.round
puts -0.3.round
#Output:
5
10.868
43.5
-12
0
If you want to round down and get the floor of a number in Ruby, you can use the floor method. If you want to round up and get the ceiling of a number in Ruby, you can use the ceil method.
Hopefully this article has been beneficial for you to learn how to use the Ruby round method to round a number to the nearest integer.