Swift Tutorial Swift References

Swift - round() Function



The Swift round() function returns an integral value that is nearest to the argument value. In halfway cases, the argument is rounded away from zero.

Syntax

In Foundation framework, it is defined as follows:

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

Parameters

x Specify a value to round.

Return Value

Returns an integral value by rounding up the x to the nearest integral value.

Example:

In the example below, round() function is used to round the given number.

import Foundation

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

The output of the above code will be:

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

❮ Swift Math Functions

5