0

I'm parsing a property list that includes and array of numbers. I then cast those numbers as an array of TimeIntervals. The array included in the .plist file reads:

[9.2,13.1,14.2,18,19.2,27.6,28.1,32.1]

The gist of the class:

class moveableElementNode: SKSpriteNode, EventListener {

  fileprivate var times = [TimeInterval]()

  func didMoveToScene() {
    unpackData()

    print(times)
  }

  func unpackData() {
    if let path = Bundle.main.path(forResource: "Data", ofType:    "plist") {
    if let dictionary = NSDictionary(contentsOfFile: path) {
      if (dictionary.object(forKey: "Data") != nil) {
        if let dataDict:[String : Any] = dictionary.object(forKey: "Data") as? [String : Any] {
          for (key, value) in dataDict {
            if key == "times" {
              times = value as! [TimeInterval]
            }
          }
        }
      }
    }
  }
}
}

For some reason when ! print the array to the console I get: [9.1999999999999993, 13.1, 14.199999999999999, 18.0, 19.199999999999999, 27.600000000000001, 28.100000000000001, 32.100000000000001]

Can anyone tell me whats going on?? Why have these single decimal place numbers been distorted?

derekFairholm
  • 285
  • 1
  • 14
  • 1
    It is because TimeInterval is a Double type, which is an "approximation" of a value. See: https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems – DonMag Jul 14 '17 at 20:07
  • Please read https://stackoverflow.com/questions/588004/is-floating-point-math-broken – vadian Jul 14 '17 at 20:10
  • 1
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Alexander Jul 14 '17 at 21:05

0 Answers0