You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Some floats change when decoded by JSONSerialization. I believe JSONSerialization is supposed to losslessly round-trip all single- and double-precision floats. The problem seems to be in the decoding, because instantiating a number directly from the encoded string doesn't exhibit this problem.
Three example values are below: One that always changes when decoded, one that changes ONLY when decoded as a root value via `allowFragments`, and one that becomes NaN when decoded (therefore failing to decode at all).
letnumber = NSNumber(value: 0.0003) // changes when decoded//let number = NSNumber(value: 0.000001) // changes when decoded as a root value//let number = NSNumber(value: Double.greatestFiniteMagnitude) // changes to NaN when decodedletencodedArray = try! JSONSerialization.data(withJSONObject: [number])
letencodedNumber = encodedArray.dropFirst().dropLast()
NSNumber(value: Double(String(data: encodedNumber, encoding: .utf8)!)!) == number// this always succeedsletdecodedArray = try! JSONSerialization.jsonObject(with: encodedArray) as! [NSNumber]
letdecodedNumber = try! JSONSerialization.jsonObject(with: encodedNumber, options: .allowFragments) as! NSNumberdecodedArray[0] == numberdecodedNumber == number
The text was updated successfully, but these errors were encountered:
0.0003 can't be exactly represented as a float value in the first place, but I guess it shouldn't actually change. cc @phausler and @itaiferber to link with other float serialization bug reports.
@belkadan I debated how explicitly I should call out that it doesn't seem like a misunderstanding of float representation on my part is the problem - but yeah, I realize the literals in my code are not exactly representable. I left them that way for brevity.
Environment
Xcode 10.1 build 10B61
Swift 4.2.1
Additional Detail from JIRA
md5: e796154a189d9afb62080e631baa45e4
Issue Description:
Some floats change when decoded by JSONSerialization. I believe JSONSerialization is supposed to losslessly round-trip all single- and double-precision floats. The problem seems to be in the decoding, because instantiating a number directly from the encoded string doesn't exhibit this problem.
Three example values are below: One that always changes when decoded, one that changes ONLY when decoded as a root value via `allowFragments`, and one that becomes NaN when decoded (therefore failing to decode at all).
The text was updated successfully, but these errors were encountered: