[swift] Convert Float to Int in Swift

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?

This question is related to swift casting type-conversion

The answer is


You can type cast like this:

 var float:Float = 2.2
 var integer:Int = Int(float)

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


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


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.


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

Var Y = Int(x);

or

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.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.


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

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()


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

var floatValue = 10.23
var intValue = Int(floatValue)

This is enough to convert from float to Int


var i = 1 as Int

var cgf = CGFLoat(i)

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

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift