I'm trying to make a calculator of growth rate (Double
) that will round the result to the nearest Integer and recalculate from there, as such:
let firstUsers = 10.0
let growth = 0.1
var users = firstUsers
var week = 0
while users < 14 {
println("week \(week) has \(users) users")
users += users * growth
week += 1
}
but I've been unable so far.
EDIT
I kinda did it like so:
var firstUsers = 10.0
let growth = 0.1
var users:Int = Int(firstUsers)
var week = 0
while users <= 14 {
println("week \(week) has \(users) users")
firstUsers += firstUsers * growth
users = Int(firstUsers)
week += 1
}
Although I don't mind that it is always rounding down, I don't like it because firstUsers
had to become a variable and change throughout the program (in order to make the next calculation), which I don't want it to happen.
Best Answer
There is a
round
available in theFoundation
library (it's actually inDarwin
, butFoundation
importsDarwin
and most of the time you'll want to useFoundation
instead of usingDarwin
directly).Running your code in a playground and then calling:
Outputs:
round()
always rounds up when the decimal place is>= .5
and down when it's< .5
(standard rounding). You can usefloor()
to force rounding down, andceil()
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 bypow(10, number of places)
:Round to 2 decimal places:
Outputs:
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.