Tidy way to switch between Double and Int

I would like to calculate an amount based on the percentage of another, however I find myself jumping between Double and Integer types and the whole thing is quite ugly, is there a more angelic way of writing the following please?

let life: Int = 83
let tomatoes: Int = 14

let yield: Double = ((Double(life) / 100.0) * Double(tomatoes))

print("Yield = \(Int(yield.rounded()))lb")
let percent = (life * tomatoes + 50) / 100
2 Likes
(83 / 100) * 14 = 11.62

(83 * 14 + 50) / 100 = 12.12

No, (83 * 14 + 50) / 100 is only integers, so the result from the integer division is 12, which is 11.62 rounded to the nearest integer.

You are right that if the resulting percent is meant to be a Double, then we should use

let percent = Double(life * tomatoes) / 100.0

But it seems like the OP wants the end result to be rounded to the nearest integer anyway:

print("Yield = \(Int(yield.rounded()))lb")

And that's probably why @Nevin suggested to do it in integers to begin with, ie:

let life: Int = 83
let tomatoes: Int = 14
print("Yield = \( (life * tomatoes + 50) / 100 )lb")

(The + 50 makes it round to nearest instead of rounding down.)

3 Likes

Thanks everybody for your thoughts, I found Jens answer my favourite:

let percent = Double(life * tomatoes) / 100.0