0

I'm trying to convert a double to a string in Swift and experiencing a significant loss in precision. Here's my code:

    var myDouble : Double = 23.00

    myDouble = myDouble / 100

    var myString : String = String(format: "%.20f", myDouble)

    println(myString)

expected result: 0.23000000000000000000

actual result: 0.23000000000000000999

Any idea what's going on?

Thanks! Mike

Michael N
  • 436
  • 5
  • 6
  • 1
    http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Martin R May 06 '15 at 21:11
  • That is to be expected! `Double` is a *binary* floating point number and ***cannot*** represent the number 0.23 exactly. – Martin R May 06 '15 at 21:11
  • Thanks Martin, that was very helpful. To expand further, using println(myDouble) gives the expected output of 0.23. I don't understand why the additional 999's are being added when the pointer is referencing 0.23. Thanks again for the help. – Michael N May 06 '15 at 21:15
  • 2
    `println()` *truncates* the output at 6 decimals, therefore it *seems* that `myDouble` is exactly 0.23. But it isn't ... – Martin R May 06 '15 at 21:24

0 Answers0