Convert Float to Int in Swift Convert Float to Int in Swift swift swift

Convert Float to Int in Swift


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)


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.51let y = Int(floor(f))

result is 10.

If you wanted to round up and convert to integer:

let f = 10.51let y = Int(ceil(f))

result is 11.

If you want to explicitly round to the nearest integer

let f = 10.51let 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.


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.2let i = Int(f.rounded(.up)) // 3

To round down use .down rule:

let f: Float = 2.2let i = Int(f.rounded(.down)) // 2

To round to the nearest integer use .toNearestOrEven rule:

let f: Float = 2.2let i = Int(f.rounded(.toNearestOrEven)) // 2

Be aware of the following example:

let f: Float = 2.5let i = Int(roundf(f)) // 3let j = Int(f.rounded(.toNearestOrEven)) // 2