How to convert float to int in Swift?


In Swift, you can convert a float to an Int by using the Int() constructor. This will round the float value toward zero and return an integer value. Remember that, this constructor returns an optional value, so you have to use an optional binding approach to wrap the value safely. In this article, you will see some examples of how to use the Int() constructor.

Using the Int() constructor

You can use the Int() constructor to convert a Float to an Int. This method rounds the float value toward zero and returns an integer value.

  • Step 1 − Declare a variable with the floating value

  • Step 2 − Convert it into integer value using Int() constructor

  • Step 3 − Print the input and output values to the console

Example

let floatValue: Float = 3.14159
let integerValue: Int = Int(floatValue)
print("Float value: \(floatValue)")
print("Integer value: \(integerValue)")

Output

Float value: 3.14159
Integer value: 3

In this example, the Int() constructor is used to convert the floatValue variable to an integer, which is then assigned to the integerValue variable. You can see the output printed on the console using the print function. After converting the float value to int, it will round off the decimal numbers.

Using the Rounded Method

The rounded method can be used to round a Float value to the nearest integer and then convert it to an Int. This method is useful when you need to round float values to the nearest integer.

  • Step 1 − Declare a variable with the floating value

  • Step 2 − Call the rounded() function to the floating value to round off the value.

  • Step 3 − Convert the rounded value into an integer value using Int() constructor

  • Step 4 − Print the input and output values to the console

Example

let floatValue: Float = 3.14159
let integerValue: Int = Int(floatValue.rounded())
print("Float value: \(floatValue)")
print("Integer value: \(integerValue)")

Output

Here is the output:
Float value: 3.14159
Integer value: 3

In this example, the floatValue variable is a Float with the value 3.14159. The rounded() method is called on this value to round it to the nearest integer. This value is then converted to an integer using the Int() constructor. The resulting integer value is assigned to the integerValue variable. The output of the program is 3.

Conclusion

In a conclusion, the Int() constructor can be used to convert a floating point value to an integer value. Also, you can round off the floating numbers before converting them into integer values. In addition to the Int() constructor, Swift also provides constructors for other integer types, such as UInt8(), Int16(), UInt32(), and so on. These constructors work in a similar way to the Int() constructor but create integers of different sizes and ranges.

Updated on: 04-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements