Swift Tutorial Swift References

Swift - trunc() Function



The Swift trunc() function is used to round the given number towards zero. It returns the nearest integral value with absolute value less than the argument.

Syntax

In Foundation framework, it is defined as follows:

public func trunc(_ __x: Double) -> Double  

Parameters

x Specify a number.

Return Value

Returns the nearest integral value with absolute value less than the argument.

Example:

In the example below, trunc() function returns the nearest integral value with absolute value less than the argument.

import Foundation

print("trunc(10.4) = \(trunc(10.4))")
print("trunc(10.6) = \(trunc(10.6))")
print("trunc(10.5) = \(trunc(10.5))")
print("trunc(11.5) = \(trunc(11.5))")
print("trunc(12.5) = \(trunc(12.5))")
print("trunc(-10.5) = \(trunc(-10.5))")
print("trunc(-11.5) = \(trunc(-11.5))")
print("trunc(-12.5) = \(trunc(-12.5))")

The output of the above code will be:

trunc(10.4) = 10.0
trunc(10.6) = 10.0
trunc(10.5) = 10.0
trunc(11.5) = 11.0
trunc(12.5) = 12.0
trunc(-10.5) = -10.0
trunc(-11.5) = -11.0
trunc(-12.5) = -12.0

❮ Swift Math Functions