Swift - nearbyint() Function
The Swift nearbyint() function returns an integral value by rounding up the specified number, using the rounding direction specified by fegetround() function.
Syntax
In Foundation framework, it is defined as follows:
public func nearbyint(_ x: CGFloat) -> CGFloat public func nearbyint(_ x: Float) -> Float public func nearbyint(_ x: Float80) -> Float80 public func nearbyint(_ __x: Double) -> Double
Parameters
x |
Specify a value to round. |
Return Value
Returns an integral value by rounding up the x, using the rounding direction specified by fegetround().
Example:
In the example below, nearbyint() function is used to round the given number.
import Foundation func Rounding_Direction_Message() { switch(fegetround()) { case FE_DOWNWARD: print("Rounding using downward method:") case FE_TONEAREST: print("Rounding using to-nearest method:") case FE_TOWARDZERO: print("Rounding using toward-zero method:") case FE_UPWARD: print("Rounding using upward method:") default: print("Rounding using unknown method:") } } Rounding_Direction_Message() print("nearbyint(10.4) = \(nearbyint(10.4))") print("nearbyint(10.6) = \(nearbyint(10.6))") print("nearbyint(10.5) = \(nearbyint(10.5))") print("nearbyint(11.5) = \(nearbyint(11.5))") print("nearbyint(-10.5) = \(nearbyint(-10.5))") print("nearbyint(-11.5) = \(nearbyint(-11.5))")
The output of the above code will be:
Rounding using to-nearest method: nearbyint(10.4) = 10.0 nearbyint(10.6) = 11.0 nearbyint(10.5) = 10.0 nearbyint(11.5) = 12.0 nearbyint(-10.5) = -10.0 nearbyint(-11.5) = -12.0
❮ Swift Math Functions