Swift
Float to Int
Type Conversion
Programming
Swift Tutorial

Convert Float to Int in Swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Converting a floating-point (Float or Double) number to an integer is a common task in Swift programming. This conversion might be necessary when dealing with values that require discrete steps or when interfacing with APIs or systems that only accept integers. Swift provides multiple ways to handle these conversions, ensuring that developers have the flexibility to choose the appropriate approach depending on the context.

Float and Double in Swift

In Swift, floating-point numbers are represented using the Float and Double data types:

  • Float: A single-precision, 32-bit floating-point number.
  • Double: A double-precision, 64-bit floating-point number.

Conversion Methods

  1. Explicit Conversion Using Int() Initializer
    The most straightforward method to convert a Float or Double to an Int is by using the Int() initializer. This method truncates the fractional part, effectively rounding towards zero.
swift
1   let floatNumber: Float = 3.7
2   let intNumber = Int(floatNumber) // intNumber is 3
3
4   let doubleNumber: Double = -2.9
5   let intNumber2 = Int(doubleNumber) // intNumber2 is -2
  1. Rounding Before Conversion
    To round a floating-point number before converting it to an Int, Swift provides rounding functions like round(), ceil(), and floor():
    • round(): Rounds to the nearest whole number.
    • ceil(): Rounds upwards to the nearest whole number.
    • floor(): Rounds downwards to the nearest whole number. Example using round():
swift
1   let floatNumber: Float = 3.7
2   let roundedIntNumber = Int(round(floatNumber)) // roundedIntNumber is 4
3
4   let doubleNumber: Double = -2.9
5   let roundedIntNumber2 = Int(round(doubleNumber)) // roundedIntNumber2 is -3
  1. Advanced Rounding Options
    Swift also allows specifying the rounding rule using the rounded(_:) method, providing options like .up, .down, .towardZero, .awayFromZero, and .toNearestOrEven.
swift
1   let floatNumber: Float = 3.6
2   let customRoundedIntNumber = Int(floatNumber.rounded(.awayFromZero)) // customRoundedIntNumber is 4
3
4   let doubleNumber: Double = -2.9
5   let customRoundedIntNumber2 = Int(doubleNumber.rounded(.awayFromZero)) // customRoundedIntNumber2 is -3

Handling Edge Cases

  1. Overflow Handling
    Attempting to initialize an Int from a very large Float or Double can result in an overflow. Swift addresses this with runtime checks that will cause a crash if overflow occurs.
  2. NaN and Infinity
    Converting NaN or infinity (Float.infinity, Double.infinity) to an Int will also result in a runtime error, since integers cannot represent these values.
swift
1   let infinity: Double = Double.infinity
2   // let intFromInfinity = Int(infinity) // This will cause a runtime error
3
4   let nanValue: Float = Float.nan
5   // let intFromNaN = Int(nanValue) // This will cause a runtime error

Summary Table

Below is a table summarizing the key points of converting Float or Double to Int in Swift:

ConceptExplanationExample Code
TruncationUses Int() initializer, discards fractional partlet intVal = Int(3.9) // intVal is 3
RoundingUses round(), ceil(), floor() methodslet intVal = Int(round(3.9)) // intVal is 4
Custom Rounding RulesUses rounded(_:) for specific roundinglet intVal = Int(3.6.rounded(.awayFromZero)) // intVal is 4
OverflowPotential runtime error with large valueslet largeNum = 1e40 // Potential overflow error when converting to Int
NaN and InfinityCannot convert, results in errorlet infiniteVal = Double.infinity // Converting to Int results in runtime error

Conclusion

Converting floating-point numbers to integers in Swift is a task that must be approached with care, understanding the implications of truncation, rounding, and the potential for runtime errors. By choosing the right method for conversion and being mindful of edge cases, developers can effectively manage this process to achieve the desired outcomes in their applications.


Course illustration
Course illustration

All Rights Reserved.