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
Use Int64
instead of Int
. Int64
can store large int values.
You can get an integer representation of your float by passing the float into the Integer initializer method.
Example:
Int(myFloat)
Keep in mind, that any numbers after the decimal point will be loss. Meaning, 3.9 is an Int of 3 and 8.99999 is an integer of 8.
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.
Just use type casting
var floatValue:Float = 5.4
var integerValue:Int = Int(floatValue)
println("IntegerValue = \(integerValue)")
it will show roundoff value eg: IntegerValue = 5 means the decimal point will be loss
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)
var i = 1 as Int
var cgf = CGFLoat(i)