Swift Tutorial Swift References

Swift - modf() Function



The Swift modf() function is used to break x into an integral and a fractional part and returns it. Both parts have the same sign as x.

Syntax

In Foundation framework, it is defined as follows:

public func modf(_ x: CGFloat) -> (CGFloat, CGFloat)

Parameters

x Specify the floating point value to break into parts.

Return Value

Returns the integral and fractional part of the x with same sign as of x.

Example:

The example below shows the usage of modf() function.

import Foundation

print("modf(10.4) = \(modf(10.4))")
print("modf(10.6) = \(modf(10.6))")
print("modf(10.5) = \(modf(10.5))")
print("modf(11.5) = \(modf(11.5))")
print("modf(-10.5) = \(modf(-10.5))")
print("modf(-11.5) = \(modf(-11.5))")

The output of the above code will be:

modf(10.4) = (10.0, 0.40000000000000036)
modf(10.6) = (10.0, 0.5999999999999996)
modf(10.5) = (10.0, 0.5)
modf(11.5) = (11.0, 0.5)
modf(-10.5) = (-10.0, -0.5)
modf(-11.5) = (-11.0, -0.5)

❮ Swift Math Functions