Swift Tutorial Swift References

Swift - remainder() Function



The Swift remainder() function returns the floating-point remainder of x/y (rounded to nearest integer). This can be mathematically expressed as below:

remainder = x - quotient * y

Where quotient is the result of x/y rounded towards nearest integer (with halfway cases rounded toward the even number).

Note: The fmod function is similar to the remainder function except the quotient is rounded towards zero instead of nearest integer. The remquo function is also very similar to the remainder function except it additionally also returns the quotient of the division operation.

Syntax

In Foundation framework, it is defined as follows:

public func remainder<T>(_ x: T, _ y: T) -> T 
//where T : FloatingPoint

Parameters

x Specify the value of numerator.
y Specify the value of denominator.

Return Value

Returns remainder of x/y. If y is zero, the function returns -nan.

Example:

In the example below, remainder() function is used to find out the remainder of a given division.

import Foundation

print("remainder(25.0, 4.0) = \(remainder(25.0, 4.0))")
print("remainder(27.0, 4.0) = \(remainder(27.0, 4.0))")
print("remainder(-7.0, 5.0) = \(remainder(-7.0, 5.0))")
print("remainder(-8.0, 5.0) = \(remainder(-8.0, 5.0))")
print("remainder(10.0, 0.0) = \(remainder(10.0, 0.0))")

The output of the above code will be:

remainder(25.0, 4.0) = 1.0
remainder(27.0, 4.0) = -1.0
remainder(-7.0, 5.0) = -2.0
remainder(-8.0, 5.0) = 2.0
remainder(10.0, 0.0) = -nan

❮ Swift Math Functions

5