by Sai gowtham

How to convert the float to Int in Swift

To convert a float value to an Int, we can use the Int() constructor by passing a float value to it.

Here is an example:

let myFloat: Float = 12.752
let myInteger = Int(myFloat)

print(myInteger)

Output:

12

Note: When we use this conversion the Integer is always rounded to the nearest downward value, like 12.752 to 12 or 6.99 to 6.

In case, if you want to round up the integer value then you can use the rounded() method like this.

let myFloat: Float = 3.4
let myInteger = Int(myFloat.rounded(.up))

Output:

4

Other example:

let myFloat: Float = 6.9
let myInteger = Int(myFloat.rounded(.up)) // 7

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course