What is the floor() function in Swift?

Overview

The floor() function in Swift returns the next largest integer that is less than or equal to a specified number.

Figure 1 shows the mathematical representation of the floor() function.

Figure 1: Mathematical representation of the "floor()" function

Note: We need to import Foundation in our code to use the floor() function. We can import it like this:
import Foundation.

Syntax


floor(number)

Parameter

This function requires a number as a parameter.

Return value

The floor() function returns the next largest integer less than or equal to the number set as a parameter.

Code example

The code written below demonstrates the use of the floor() function in Swift:

import Swift
//header for function
import Foundation
//integer
print ("The value of floor(4.0) : ",floor(4.0));
//positive double value
print ("The value of floor(2.56) : ",floor(2.56));
//negative double value
print ("The value of floor(-2.56) : ",floor(-2.56));

Code explanation

Line 3: We add the header Foundation required for the floor() function.

Line 6: We calculate the floor of the integer values using the floor() function.

Line 9: We calculate the floor of the positive double value using the floor() function.

Line 12: We calculate the floor of the negative double value using the floor() function.

Free Resources