2

I am getting an unexpected result and I can't figure out why. In the following Swift code I am subtracting doubles in a while loop and I am expecting the results to always be x.55 since I am only subtracting 5.00 each time, but on the last iteration the result is adding a bunch of additional numbers after the decimal and I can't figure out why.

Can anyone point me in the right direction here? What do I need to do differently if I want the result to always be exact to two decimal places?

Here is the example code:

var testValue1 = 5.00
var testValue2 = 15.55

while testValue2 >= testValue1 {
    testValue2 = testValue2 - testValue1
    println("testValue2: \(testValue2)")
}

And here is the Console output: testValue2: 10.55 testValue2: 5.55 testValue2: 0.550000000000001

(I expected the Console output to be: 10.55, 5.55, 0.55)

1 Answers1

3

Here is the final solution :)

var testValue1 = 5.00
var testValue2 = 15.55

while testValue2 >= testValue1 {
    testValue2 = testValue2 - testValue1
    var s = NSString(format: "%0.2f", testValue2)
    println("testValue2: \(s)")
}

Kudos to Thomas Kilian for letting me know how to implement my logic!

  • Try `let s = NSString(format: "%2.2f", testValue2); println("testValue2: \(s)")` – qwerty_so Dec 07 '14 at 16:48
  • What is really needed is to round the number to the desired number of decimal places, not relying on a format or print statement. – zaph Dec 07 '14 at 17:05
  • @Zaph Hey , it still serves the purpose as he wants to display the result as 2 decimal places –  Dec 07 '14 at 17:07