print(String(Float(2 * (10 / 9))))
Why does this code print "2.0"?
Using a calculator, "2 * (10 / 9)" would equal 2.222222.....
print(String(Float(2 * (10 / 9))))
Why does this code print "2.0"?
Using a calculator, "2 * (10 / 9)" would equal 2.222222.....
You are calculating with integer numbers and cast the (integer) result to Float
.
Do your calculation with floating point types (Double
) instead:
print(String(Float(2.0 * (10.0 / 9.0))))
No need to cast though:
print(2.0 * (10.0 / 9.0))
2.0 * (10.0 / 9.0) would give your the expected result.
In your case, Swift does the calculations based on Integers first (result = 2), then converts this to a float (result = 2.0) and this into a String (result = "2.0")
To get the correct result, it should read:
print(String(Float(2.0 * (10.0 / 9.0))))
You then could leave out the two type conversations:
print(2.0 * (10.0 / 9.0))