Convert Float to Int in Swift
Asked Answered
E

15

228

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 floats and ints in Objective-C

var float: Float = 2.2
var integer: Int = float as Float

But this produces the following error message:

'Float' is not convertible to 'Int'

Any idea how to property convert from Float to Int?

Edelweiss answered 4/6, 2014 at 5:46 Comment(3)
the as operator is for down-casting to subclasses. ie: UIView as UIButtonTrimurti
in swift, you can do type casting using the as keyword or optional as (as?) such as 4 as? String, if 4 can be a string it will work but if it's not it will not work. I bring this up because you use the word "casting" in your question and i didn't want you to be confused. :3Sands
Your code doesn't make sense. (float as Float) does nothing because float is of type Float already. You either meant var integer: Int = float (same error) or var integer: Int = float as Int.Steeve
C
350

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)
Chambermaid answered 4/6, 2014 at 5:59 Comment(4)
@paulm - I had not tried (above code in comment). but might be it will work for us (not sure).Chambermaid
The cast is enough for the Swift compiler to intuit the variable type, so you do not need to explicitly declare the type. var myIntValue = Int(myFloatValue) works.Milanmilanese
(swift 2.0) it's better to check if the float value is a finite value, if myFloatvalue.isFinite {...}Carcajou
This code will crash for large values like Int(Float.greatestFiniteMagnitude).Capstan
T
136

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.

Taxdeductible answered 28/6, 2014 at 13:17 Comment(4)
Yeah, it's really worth noting that Int() simply cuts the fractional part, which usually isn't the desired behaviour ;) Int(round(f)) does the job.Sensitive
Or ceil ()to round the value upwards.Apish
Edge case: round(10.5) == 11.0Platus
let y = Int(round(f)) can also be written as let y = lround(f)Lucknow
A
35

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
Aerology answered 3/11, 2016 at 10:9 Comment(1)
This should be the best answer, since it raises the awareness of rounding and its related API, so that the developer can take more control and responsibility. FloatingPointRoundingRuleFerous
F
29

Converting is simple:

let float = Float(1.1) // 1.1
let int = Int(float) // 1

But it is not safe:

let float = Float(Int.max) + 1
let int = Int(float)

Will due to a nice crash:

fatal error: floating point value can not be converted to Int because it is greater than Int.max

So I've created an extension that handles overflow:

extension Double {
    // If you don't want your code crash on each overflow, use this function that operates on optionals
    // E.g.: Int(Double(Int.max) + 1) will crash:
    // fatal error: floating point value can not be converted to Int because it is greater than Int.max
    func toInt() -> Int? {
        if self > Double(Int.min) && self < Double(Int.max) {
            return Int(self)
        } else {
            return nil
        }
    }
}


extension Float {
    func toInt() -> Int? {
        if self > Float(Int.min) && self < Float(Int.max) {
            return Int(self)
        } else {
            return nil
        }
    }
}

I hope this can help someone

Faden answered 28/8, 2015 at 19:18 Comment(0)
H
7

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.

Hebron answered 5/6, 2014 at 16:59 Comment(1)
And use Int(MyFloat + .5) for rounding.Penguin
M
6

Like this:

var float:Float = 2.2 // 2.2
var integer:Int = Int(float) // 2 .. will always round down.  3.9 will be 3
var anotherFloat: Float = Float(integer) // 2.0
Millet answered 4/6, 2014 at 5:50 Comment(0)
S
4

Use a function style conversion (found in section labeled "Integer and Floating-Point Conversion" from "The Swift Programming Language."[iTunes link])

  1> Int(3.4)
$R1: Int = 3
Separator answered 4/6, 2014 at 5:49 Comment(0)
G
1

You can type cast like this:

 var float:Float = 2.2
 var integer:Int = Int(float)
Grizzly answered 4/6, 2014 at 5:51 Comment(0)
L
1

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

Lyrism answered 4/11, 2014 at 8:38 Comment(0)
S
1
var floatValue = 10.23
var intValue = Int(floatValue)

This is enough to convert from float to Int

Senecal answered 10/2, 2015 at 8:56 Comment(0)
V
1

Suppose you store float value in "X" and you are storing integer value in "Y".

Var Y = Int(x);

or

var myIntValue = Int(myFloatValue)
Veracity answered 23/6, 2016 at 9:22 Comment(0)
S
0
var i = 1 as Int

var cgf = CGFLoat(i)
Subulate answered 23/6, 2015 at 8:12 Comment(0)
C
0

Most of the solutions presented here would crash for large values and should not be used in production code.

If you don't care for very large values use this code to clamp the Double to max/min Int values.

let bigFloat   = Float.greatestFiniteMagnitude
let smallFloat = -bigFloat

extension Float {
    func toIntTruncated() -> Int {
        let maxTruncated  = min(self, Float(Int.max).nextDown)
        let bothTruncated = max(maxTruncated, Float(Int.min))
        return Int(bothTruncated)
    }
}

// This crashes:
// let bigInt = Int(bigFloat)

// this works for values up to 9223371487098961920
let bigInt   = bigFloat.toIntTruncated()
let smallInt = smallFloat.toIntTruncated()

Capstan answered 19/2, 2021 at 22:25 Comment(0)
K
0

You can make a handy extension using computed property and use it from any where in project

    extension Float{
    
    var toInt : Int{
       return Int(self)
    }
    
}

Calling

private var call: Float = 55.9
print(call.toInt)
Knives answered 8/10, 2022 at 13:55 Comment(0)
Z
-1

Use Int64 instead of Int. Int64 can store large int values.

Zarf answered 16/5, 2016 at 15:17 Comment(1)
you mean, for the original question, or for the problem with Float having a value range larger than Int ?Scalade

© 2022 - 2024 — McMap. All rights reserved.