Reputation: 596
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
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