Swift does not mix integer and floating-point values automatically. Convert explicitly when an expression needs a different numeric type.

Convert before dividing

totalPoints
numeric_conversion.swift
Replay: real traced execution (multi-file project)
let totalPoints = 17
let attempts = 4
let average = Double(totalPoints) / Double(attempts)
let tenths = Int(average * 10)
let rounded = Double(tenths) / 10.0

print("points=\(totalPoints)")
print("average=\(rounded)")
let totalPoints = 9
let attempts = 4
let average = Double(totalPoints) / Double(attempts)
let tenths = Int(average * 10)
let rounded = Double(tenths) / 10.0

print("points=\(totalPoints)")
print("average=\(rounded)")
let totalPoints = 23
let attempts = 4
let average = Double(totalPoints) / Double(attempts)
let tenths = Int(average * 10)
let rounded = Double(tenths) / 10.0

print("points=\(totalPoints)")
print("average=\(rounded)")
  1. totalPoints ← 17, attempts ← 4, average ← 4.25, tenths ← 42, rounded ← 4.2

    1let totalPoints→ 17 = 17  //@totalPoints=9, 232let attempts→ 4 = 43let average→ 4.25 = Double(totalPoints17) / Double(attempts4)4let tenths→ 42 = Int(average4.25 * 10)5let rounded→ 4.2 = Double(tenths42) / 10.067print("points=\(totalPoints17)")8print("average=\(rounded4.2)")
    outputpoints=17
    average=4.2
  1. totalPoints ← 9, attempts ← 4, average ← 2.25, tenths ← 22, rounded ← 2.2

    1let totalPoints→ 9 = 92let attempts→ 4 = 43let average→ 2.25 = Double(totalPoints9) / Double(attempts4)4let tenths→ 22 = Int(average2.25 * 10)5let rounded→ 2.2 = Double(tenths22) / 10.067print("points=\(totalPoints9)")8print("average=\(rounded2.2)")
    outputpoints=9
    average=2.2
  1. totalPoints ← 23, attempts ← 4, average ← 5.75, tenths ← 57, rounded ← 5.7

    1let totalPoints→ 23 = 232let attempts→ 4 = 43let average→ 5.75 = Double(totalPoints23) / Double(attempts4)4let tenths→ 57 = Int(average5.75 * 10)5let rounded→ 5.7 = Double(tenths57) / 10.067print("points=\(totalPoints23)")8print("average=\(rounded5.7)")
    outputpoints=23
    average=5.7

Follow the Conversion

  1. totalPoints starts at 17.
  2. attempts is 4.
  3. average = Double(totalPoints) / Double(attempts) gives 4.25.
  4. tenths = Int(average * 10) keeps 42.
  5. rounded becomes 4.2, so the program prints average=4.2. | totalPoints | attempts | average before tenths | printed average | | --- | --- | --- | --- | | 9 | 4 | 2.25 | 2.2 | | 17 | 4 | 4.25 | 4.2 | | 23 | 4 | 5.75 | 5.7 |
conversion Use constructors such as `Double(count)` when an expression needs a different numeric type.

Exercise: numeric_conversion.swift

Reproduce points=17 and average=4.2, then use totalPoints 9 and 23 to predict each printed average.