There is a round
available in the Foundation
library (it's actually in Darwin
, but Foundation
imports Darwin
and most of the time you'll want to use Foundation
instead of using Darwin
directly).
import Foundation
users = round(users)
Running your code in a playground and then calling:
print(round(users))
Outputs:
15.0
round()
always rounds up when the decimal place is >= .5
and down when it's < .5
(standard rounding). You can use floor()
to force rounding down, and ceil()
to force rounding up.
If you need to round to a specific place, then you multiply by pow(10.0, number of places)
, round
, and then divide by pow(10, number of places)
:
Round to 2 decimal places:
let numberOfPlaces = 2.0
let multiplier = pow(10.0, numberOfPlaces)
let num = 10.12345
let rounded = round(num * multiplier) / multiplier
print(rounded)
Outputs:
10.12
Note: Due to the way floating point math works, rounded
may not always be perfectly accurate. It's best to think of it more of an approximation of rounding. If you're doing this for display purposes, it's better to use string formatting to format the number rather than using math to round it.
For nonnegative integers, the following function gives
the desired result in pure integer arithmetic :
func divideAndRound(numerator: Int, _ denominator: Int) -> Int {
return (2 * numerator + denominator)/(2 * denominator)
}
Examples:
print(20000.0/7000.0) // 2.85714285714286
print(divideAndRound(20000, 7000)) // 3 (rounded up)
print(10000.0/7000.0) // 1.42857142857143
print(divideAndRound(10000, 7000)) // 1 (rounded down)
The idea is that
a 1 2 * a + b
- + - = ---------
b 2 2 * b
And here is a possible implementation for arbitrarily signed
integers which also does not overflow:
func divideAndRound(num: Int, _ den: Int) -> Int {
return num / den + (num % den) / (den / 2 + den % 2)
}
(Based on @user3441734's updated solution, so we have a reference
cycle between our answers now :)
There is also a ldiv
function which computes both quotient
and remainder of a division, so the last function could also be
implemented as
func divideAndRound(num: Int, _ den: Int) -> Int {
let div = ldiv(num, den)
let div2 = ldiv(den, 2)
return div.quot + div.rem / (div2.quot + div2.rem)
}
(I did not test which version is faster.)
Best Answer
Swift 3:
Swift 2: