Swift Tutorial Swift References

Swift - fmod() Function



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

fmod = x - tquot * y

Where tquot is the result of x/y rounded toward zero.

Note: The remainder function is similar to the fmod function except the quotient is rounded to the nearest integer instead of towards zero.

Syntax

In Foundation framework, it is defined as follows:

public func fmod<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, fmod() function is used to find out the remainder of a given division.

import Foundation

print("fmod(25.0, 4.0) = \(fmod(25.0, 4.0))")
print("fmod(27.0, 4.0) = \(fmod(27.0, 4.0))")
print("fmod(-6.0, 5.0) = \(fmod(-6.0, 5.0))")
print("fmod(-9.0, 5.0) = \(fmod(-9.0, 5.0))")
print("fmod(10.0, 0.0) = \(fmod(10.0, 0.0))")

The output of the above code will be:

fmod(25.0, 4.0) = 1.0
fmod(27.0, 4.0) = 3.0
fmod(-6.0, 5.0) = -1.0
fmod(-9.0, 5.0) = -4.0
fmod(10.0, 0.0) = -nan

❮ Swift Math Functions