0

I try to use swift code to calculate 10 * 75% = 7.5

var b : Int = 10
var a : Int = 75
// result x is 0
var x = b * (a / 100) 

However the result is zero. How to get 7.5 result without changing the type and value of a and b?

UPDATE:

I got it right by:

 var x: Double = (Double(b) * (Double(a) / 100)) // x is 7.5

Now, how can I round it to 8 as a Int type?

Leem
  • 17,220
  • 36
  • 109
  • 159

3 Answers3

0

You're using integer (i.e. whole number) arithmetic, when what you want is floating-point arithmetic. Change one of the types to Float, and Swift will figure out that x is also a Float.

var b : Int = 10
var a : Int = 75
var x = Float(b) * (Float(a) / 100.0) // now x is a Float (.75)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
NRitH
  • 13,441
  • 4
  • 41
  • 44
0

Ok then you just need to do:

var b : Int = 10
let c = (Double(b) * 0.75)
let restult = ceil(c)
Norman G
  • 759
  • 8
  • 18
0

For doing arithmetic in Swift, both sides of the equation must be using the same type. Try using this code:

let b = 10.0
let a = 75.0
let x = b * (a / 100.0
print(x)

7.5

To make it round up, use the built in ceil function

print(ceil(x))

8.0

Scriptable
  • 19,402
  • 5
  • 56
  • 72