0

I ran into a strange (at least for me) issue with Xcode and Swift 2. If you try to run this into a playground (or in a project, it doesn't matter), the values printed are quite a bit off what I am expected. At least one is, when it should be 0.

func run() {
    var test : Float = 0.5

    while test > 0 {
        test -= 0.1
        print(test)
    }
}

run()

This prints the following values:

0.4
0.3
0.2
0.1
1.49012e-08
-0.1

I would of course, expect a 0. What's a bit even stranger is that if you print(0.1 - 0.1) it correctly logs 0.0. It really doesn't matter if you change the test var to Double (the value printed is doubled though, 2....). Nor if you force the casting of the decrimental value to Float (or Double). The only workaround I found was to make them all ints then cast to float by dividing with 10.

Any help would be much appreciated!

Razvan Soneriu
  • 587
  • 3
  • 7
  • 23

0 Answers0