Returns this value rounded to an integral value using the specified rounding rule.
SDK
- Xcode 9.0+
Framework
- Swift Standard Library
Declaration
func rounded(_ rule: Floating Point Rounding Rule) -> Double
Parameters
ruleThe rounding rule to use.
Return Value
The integral value found by rounding using rule.
Discussion
The following example rounds a value using four different rounding rules:
let x = 6.5
// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"
// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"
// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"
// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"
For more information about the available rounding rules, see the Floating enumeration. To round a value using the default “schoolbook rounding”, you can use the shorter rounded() method instead.
print(x.rounded())
// Prints "7.0"