Convert Float to Int in Swift
Explicit Conversion
Converting to Int will lose any precision (effectively rounding down). By accessing the math libraries you can perform explicit conversions. For example:
If you wanted to round down and convert to integer:
let f = 10.51
let y = Int(floor(f))
result is 10.
If you wanted to round up and convert to integer:
let f = 10.51
let y = Int(ceil(f))
result is 11.
If you want to explicitly round to the nearest integer
let f = 10.51
let y = Int(round(f))
result is 11.
In the latter case, this might seem pedantic, but it's semantically clearer as there is no implicit conversion...important if you're doing signal processing for example.
You can convert Float
to Int
in Swift like this:
var myIntValue:Int = Int(myFloatValue)
println "My value is \(myIntValue)"
You can also achieve this result with @paulm's comment:
var myIntValue = Int(myFloatValue)