OneBite.Dev - Coding blog in a bite size

Convert Variable From Float To Int In Swift

Code snippet for how to Convert Variable From Float To Int In Swift with sample and detail explanation

Converting data types is a common procedure in coding, especially when dealing with numerical inputs that can be represented in different ways. This article specifically focuses on converting a variable from a float to an int data type using Swift programming language.

Code Snippet

In Swift, converting a Float into an Int is straightforward. Below is how to achieve it:

let floatValue: Float = 23.67
let intValue: Int = Int(floatValue)
print(intValue)

Code Explanation

The first line of code essentially declares and initializes a new variable named ‘floatValue’ with a float data type and assigns it a value of 23.67. Being a floating-point number, 23.67 contains decimal places-details that will be lost in the conversion process.

The second line of code is where the conversion actually takes place. We’re declaring and initializing a new variable named ‘intValue’. Then, with the use of the ‘Int’ type method, we’re converting the float value contained in ‘floatValue’ into an integer.

It should be noted that Swift’s conversion from float to int is not rounding the value but truncating it. In this case, the result will be 23, not 24. After the conversion, all decimal points are lost and ignored. In our case, .67 is not taken into consideration, and the ‘intValue’ will simply be 23; which will be printed on the console as the output.

Remember, Swift’s type safety insists that we explicitly define the type of data being converted; hence, the use of ‘Int’ to inform Swift that the conversion is going to an Integer. This concept is notably different from other languages that might perform automatic type conversion. Always keep Swift’s type safety principles in mind while working with data types in this language.

swift