To round a double to the nearest integer, just use round()
.
var x = 3.7
x.round() // x = 4.0
If you don't want to modify the original value, then use rounded()
:
let x = 3.7
let y = x.rounded() // y = 4.0. x = 3.7
As one might expect (or might not), a number like 3.5
is rounded up and a number like -3.5
is rounded down. If you need different rounding behavior than that, you can use one of the rounding rules. For example:
var x = 3.7
x.round(.towardZero) // 3.0
If you need an actual Int
then just cast it to one (but only if you are certain that the Double won't be greater than Int.max
):
let myInt = Int(myDouble.rounded())
round
, lround
, floor
, and ceil
. However, now that Swift has this functionality built in, I can no longer recommend using those functions. Thanks to @dfri for pointing this out to me. Check out @dfri's excellent answer here. I also did something similar for rounding a CGFloat
.