I want to convert a Float
to an Int
in Swift. Basic casting like this does not work because these types are not primitives, unlike float
There are lots of ways to round number with precision. You should eventually use swift's standard library method rounded()
to round float number with desired precision.
To round up use .up
rule:
let f: Float = 2.2
let i = Int(f.rounded(.up)) // 3
To round down use .down
rule:
let f: Float = 2.2
let i = Int(f.rounded(.down)) // 2
To round to the nearest integer use .toNearestOrEven
rule:
let f: Float = 2.2
let i = Int(f.rounded(.toNearestOrEven)) // 2
Be aware of the following example:
let f: Float = 2.5
let i = Int(roundf(f)) // 3
let j = Int(f.rounded(.toNearestOrEven)) // 2