How to Convert Float to Int in swift with example

Int contains numbers without decimal values. Example int values are 45,7. The float contains numbers with decimal floating values. Example float values are 123.11,56.77.

Int and Float are inbuilt types in Swift language.

This tutorial explains multiple ways to convert Float to Int and Int to Float in Swift with examples

How to Convert Int to Float in swift

Swift Float has a constructor that takes int number You can check variable type in swift using the type(of:) function.

Here is an example

let number = 123
print(number) //123
print(type(of:number))//Int

let numberWithDecimal = Float(number)
print(numberWithDecimal) //123.0
print(type(of:numberWithDecimal))// Float

Int has different types such as signed types(Int, Int8, Int16, Int32, and Int64) and unsigned types(UInt, UInt8, UInt16, UInt32, and UInt64)

Float constructor accepts any both signed and unsigned int.

Here is an example of Converting UInt and Int64 into Float in Swift with examples

let number: UInt8 = 123
print(number) //123
print(type(of:number))//UInt8
let numberWithDecimal = Float(number)
print(type(of:numberWithDecimal))// Float

print(numberWithDecimal) //123.0

let number1: Int64 = -78
print(number1) //-78
print(type(of:number1))//Int64
let numberWithDecimal1 = Float(number1)
print(numberWithDecimal1) //-78
print(type(of:numberWithDecimal1))// Float

Output:

123
UInt8
123.0
-78
Int64
Float
-78.0
Float

How to Convert Float to Int in swift

Converting float to int results number without precision.

the precision number converted to int in either

  • to round up
  • to round down
  • to the nearest values
  • ignore precision

Floating value can be converted to Int with the below ways.

Here is an example converted to Int by omitting precision.

It uses an Int constructor with Float values

let price: Float = 12.78
print(price) //12.78
print(type(of:price))// Float

let result = Int(price)
print(type(of:result))// Int
print(result) //12

Here is a Float to Int with round up example

let price: Float = 12.78
print(price) //12.78
print(type(of:price))// Float

let result = Int(price.round(.up))
print(type(of:result))// Int
print(result) //13

Float to Int with round down example in swift

let price: Float = 12.78
print(price) //12.78
print(type(of:price))// Float

let result = Int(price.round(.down))
print(type(of:result))// Int
print(result) //12

here is an example converted to the nearest number

let price: Float = 12.78
print(price) //12.78
print(type(of:price))// Float

let result = Int(price.round(.toNearestOrEven))
print(type(of:result))// Int
print(result) //12

Conclusion

Learned multiple ways to convert the precision floating value to number in swift.