doodle911 doodle911 - 5 months ago 23
Swift Question

Swift Math Answering 0

I am trying to calculate a percentage of how many spaces are available in green street. When I do the calculation (greenStreetSpaces / greenStreetTotalSpaces) * 100 the returned answer is 0.

Here is my code

var greenStreetSpaces = json["carparkData"]["Jersey"]["carpark"][0]["spaces"].intValue
print(greenStreetSpaces)
var greenStreetTotalSpaces = 608
print(greenStreetTotalSpaces)

let greenStreetPercent = (greenStreetSpaces / greenStreetTotalSpaces) * 100
print(greenStreetPercent)


and the console from me printing the results.

The snippet of relevant results on the console

Answer

This operator "/" applied to 2 integers returns the integer part of the division

Example

let greenStreetSpaces = 10
let greenStreetTotalSpaces = 15

greenStreetSpaces / greenStreetTotalSpaces // 0

To solve the problem you should divide Doubles

(Double(greenStreetSpaces) / Double(greenStreetTotalSpaces)) * 100 // 66.66666666666666