Skip to content

Instantly share code, notes, and snippets.

@prachigauriar
Last active February 21, 2018 22:51
Show Gist options
  • Save prachigauriar/a01e94b2696d937418a40eccd40d1d1e to your computer and use it in GitHub Desktop.
Save prachigauriar/a01e94b2696d937418a40eccd40d1d1e to your computer and use it in GitHub Desktop.
JSONDecoder Decimal Error
import Foundation
struct DoubleItem : Codable {
var name: String
var price: Double
}
struct DecimalItem : Codable {
var name: String
var price: Decimal
}
let jsonString = """
{ "name": "Gum ball", "price": 0.1 }
"""
let jsonData = jsonString.data(using: .utf8)!
let decoder = JSONDecoder()
do {
let doubleItem = try decoder.decode(DoubleItem.self, from: jsonData)
print(doubleItem)
let decimalItem = try decoder.decode(DecimalItem.self, from: jsonData)
print(decimalItem)
} catch {
print(error)
}
// Output Xcode 9b3:
// DoubleItem(name: "Gum ball", price: 0.10000000000000001)
// typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [Optional(__lldb_expr_5.DecimalItem.(CodingKeys in _AEF227D1F6EED9315B49119185CDD264).price)], debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead."))
// Output Xcode 9b4:
// DoubleItem(name: "Gum ball", price: 0.10000000000000001)
// DecimalItem(name: "Gum ball", price: 0.1)
@duannguyenle
Copy link

duannguyenle commented Feb 8, 2018

// Output Xcode 9.2 (9C40b):
// DoubleItem(name: "Gum ball", price: 0.10000000000000001)
// DecimalItem(name: "Gum ball", price: 0.1)

But if price = 9.37, the error would still be there:
// DoubleItem(name: "Gum ball", price: 9.3699999999999992)
// DecimalItem(name: "Gum ball", price: 9.369999999999997952)

@tib
Copy link

tib commented Feb 21, 2018

// Output Xcode 9.2 (9C40b):
// Apple Swift version 4.0.3 (swiftlang-900.0.74.1 clang-900.0.39.2)
//{ "name": "Gum ball", "price": 46.984765 }
DoubleItem(name: "Gum ball", price: 46.984765000000003)
DecimalItem(name: "Gum ball", price: 46.98476500000001024)

Same output with 4.1 swift-DEVELOPMENT-SNAPSHOT-2018-02-20-a-ubuntu16.04.
Is this a Swift / foundation bug or an intended behavior?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment