← Back to Swift Course | Chapter 2: Variables & Types | Lesson 5 of 8

Doubles and Floats

Doubles and floats are numbers that can have a decimal point, like 3.14 or 0.5.

Declaring Doubles

Double is Swift's default floating-point type, used automatically when a literal contains a decimal point.

Example: Declaring Doubles

markup
let price = 19.99
let taxRate = 0.08
print("Price: \(price), tax rate: \(taxRate)")

Float vs Double

Float uses less memory (32 bits) but has less precision than Double (64 bits). Swift infers Double by default, so Float must be requested with an explicit annotation.

Example: Float vs Double

markup
let preciseValue: Double = 3.14159265358979
let lessPrecise: Float = 3.14159265358979
print("Double: \(preciseValue)")
print("Float: \(lessPrecise)")

Converting Between Int and Double

Swift never silently converts between numeric types; you must explicitly wrap a value, such as Double(someInt), to convert an integer into a floating-point number for calculations.

Note: Without Double(items), dividing a Double by an Int would not even compile -- Swift requires matching types.

Example: Converting Between Int and Double

markup
let items = 3
let totalCost = 10.0
let average = totalCost / Double(items)
print("Average cost per item: \(average)")
Common Mistakes
  1. Comparing two Double values with == after arithmetic and expecting exact equality, when floating-point rounding can make them differ slightly.
  2. Using Float when Double is intended; Double is Swift's default and has more precision, so mixing them requires explicit conversion.
  3. Dividing two Int values expecting a decimal result, forgetting that Int / Int truncates instead of producing a Double.
Chapter Summary
  • Double is a 64-bit floating-point type and Swift's default choice for decimal numbers.
  • Float is a 32-bit floating-point type, less precise but sometimes used to save memory.
  • Floating-point arithmetic can have small rounding errors, so avoid exact == comparisons.
  • Converting an Int to a Double requires an explicit Double(someInt) call.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.