0

I create an array called testArray. I then save it to user defaults. And retrieve it from user defaults. When I log the original "testArray" and log the retrieved "retrieveArray", the longitude and latitude fields have changed.

For example:

testArray: "longitude": 31.132013199999999

retrievedArray: "longitude": 31.1320132

Why is this? And stranger still - why is the retrieved array logging correctly, but the original array is getting logged with extra decimal places?

Thank you.

let testarray =
Array(
arrayLiteral:
["longitude":31.1320132],
["longitude":31.1320132],
["longitude":31.1320132],
["longitude":31.1320132])

UserDefaults.standard.set(testarray, forKey: "myTestArray")

let retrievedArray = UserDefaults.standard.value(forKey:"myTestArray")

NSLog((testarray as! Array<Dictionary<String,Any>>)[2].description)

NSLog((retrievedArray as! Array<Dictionary<String,Any>>)[2].description)

OUTPUT

app[75897:9783167] ["longitude": 31.132013199999999]

app[75897:9783167] ["longitude": 31.1320132]

UPDATE: Some have said that "duplicate question" is used too aggressively on StackOverflow, and I have noticed that at times. But in this case, yes! This "duplicate question" does seem to speak to the issue. Thank you.

1 Answers1

1

This is a round-off error.

I suggest that you convert the double to string, or round the value. You can see many solutions where.

Community
  • 1
  • 1
macabeus
  • 4,156
  • 5
  • 37
  • 66
  • Thank you Macabeus. How does the rounding enter the picture? In the examples in the "where" link you provided, they all explicitly contain a direct reference to rounding. In the code I have posted, there is no call to a rounding function or property. Are you saying the rounding is being done automatically? What seems confusing is that if this is a rounding error, it is happening on a literal value which I declare and then output to the console without rounding it. Thanks! – Mark Purpelio May 01 '17 at 20:59