What is ceil() in Ruby?

The ceil() function returns the smallest integer that is greater than or equal to the number whose ceiling needs to be calculated.

Figure 1 shows the mathematical representation of the ceil() function and the corresponding expression in Ruby.

Figure 1: Mathematical representation of ceil() function and the corresponding expression in Ruby

Syntax

num.ceil(digits)
# where num is a number to round up
#where digits is the number of decimal places to which the precision is to be kept

Parameter

This function requires n digits to which the precision of decimal digits is kept. This is optional, and if its value is omitted, then its default value is 0.

Return value

ceil() returns an integer that represents the ceiling of the value to which the function is applied.

Example

The example shows how we can use the ceil() function in Ruby.

#The following code rounds up 17.321 to 2 decimal places
(17.321).ceil(2) => 17.33

#In the case if '-n' is sent as digits to the function then, it rounds up the number to n number of digits to the left of decimal places
(18).ceil(-1) => 10
#positive integer
num1=10
print "num1.ceil() : ", num1.ceil(), "\n"
#negative integer
num2=-10
print "num2.ceil() : ", num2.ceil(), "\n"
#positive float value
num3=2.1
print "num3.ceil() : ", num3.ceil(), "\n"
#negative float value
num4=-2.1
print "num4.ceil() : ", num4.ceil(), "\n"

Free Resources