0
print(String(Float(2 * (10 / 9))))

Why does this code print "2.0"?
Using a calculator, "2 * (10 / 9)" would equal 2.222222.....

shallowThought
  • 19,212
  • 9
  • 65
  • 112
  • @MartinR is this related to the issue that I faced couple weeks ago (I assume that you forgot about it), which is floating point numbers are represented as scientific notations? – Ahmad F Jan 08 '17 at 08:53
  • @AhmadF: Sorry, I don't know what issue you are talking of. – But this is unrelated to floating point numbers or scientific notation. `10 / 9` is a integer division and evaluates to `1` in Swift and in many other programming languages. – Martin R Jan 08 '17 at 09:58
  • @MartinR Thank you for your response, my issue was how can I count the number of the digits after the "." (on the right side) in floating points, you and Rob told me it is not possible and -thankfully- my question marked as duplicated to [this one](http://stackoverflow.com/questions/588004/is-floating-point-math-broken). – Ahmad F Jan 08 '17 at 10:03

2 Answers2

3

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))
shallowThought
  • 19,212
  • 9
  • 65
  • 112
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))
jboi
  • 11,324
  • 4
  • 36
  • 43