swiftlang / swift-foundation

The Foundation project
Apache License 2.0
2.4k stars 159 forks source link

JSON encoding of `Double` differs between platforms #358

Open amomchilov opened 10 months ago

amomchilov commented 10 months ago

I opened this issue kishikawakatsumi/swift-power-assert#436 about some failing unit tests, and it turns out to be platform dependant. From that thread:

iOS 17, Sonoma and Linux

{"foundingYear":1957,"location":{"longitude":139.745438,"latitude":35.658581},"name":"Tokyo > Tower"}

iOS 16.x and macOS Monterey

{"name":"Tokyo Tower","location":{"longitude":139.74543800000001,"latitude":35.658580999999998},"foundingYear":1957}

Given the OSes impacted, I'm guessing this was causing by the transition to the Swift-native Foundation impl on Apple platforms.

Is this difference in Double formatting intentional?

SwiftFiddle

demo.swift ```swift import Foundation struct Coordinate: Codable { var latitude: Double var longitude: Double } struct Landmark: Codable { var name: String var foundingYear: Int var location: Coordinate } let landmark = Landmark( name: "Tokyo Tower", foundingYear: 1957, location: Coordinate(latitude: 35.658581, longitude: 139.745438) ) let data = try JSONEncoder().encode(landmark) print(String(data: data, encoding: .utf8)!) print(data.count) print(data as NSData) // NSData gives a better description ```
iCharlesHu commented 10 months ago

@kperryua could you please take a look?