Tuan Huynh
Tuan Huynh

Reputation: 596

Mul 2 number as Double and Int in Swift

How to convert the following code from java to Swift, they have results different.

//Java

int x = 100;
x -= (0.65 * 19);
System.out.println(x);    // 87

//Swift

var z : Int = 100
z -= Int(0.65 * 19)
print(z)                 // 88

Upvotes: 1

Views: 286

Answers (1)

Martin R
Martin R

Reputation: 539725

In Java mixed integer/double arithmetic, all operands are converted to double first. So x is converted to a double, then (0.65 * 19) is subtracted (resulting in 87.65), finally the result is truncated to an int (resulting in 87) and assigned to x again.

There is no implicit type conversion in Swift. In

z -= Int(0.65 * 19)

you are truncating the result of the multiplication to 12 before it is subtracted from 100.

In order to get the same result as in Java, you have to do the same conversions explicitly:

var z : Int = 100
z = Int(Double(z) - 0.65 * 19)
print(z) // 87

Upvotes: 2

Related Questions