Losing precision when passing numbers through the JSONDecoder in Swift 4

I'm sending some JSON data to our server and in the process having issues when encoding certain values with the new Swift 4 JSONDecoder. Take this playground example:

import Foundation

struct QuantyTest: Codable {
    var name: String
    var value: Float
}

let json = """
[
    {
        "name": "Length",
        "value": 9.87
    },
    {
        "name": "Width",
        "value": 9.95
    }
]
""".data(using: .utf8)!

let decoder = JSONDecoder()
var size = try decoder.decode([QuantyTest].self, from: json)
let encoder = JSONEncoder()
var encodSize = try? encoder.encode(size)
print(String(data: encodSize!, encoding: .utf8)!)

So I first decode the JSON and print out the result (size). The output for looks like this:

[{name "Length", value 9.87}, {name "Width", value 9.95}]

All good, but when I encode (size) back to JSON using the Swift JSONEncoder I get the following output:

[{"name":"Length","value":9.869999885559082},{"name":"Width","value":9.9499998092651367}]

I've tried changing value to be decimal or double but I have similar problems, the decimal output look like this:

[{"name":"Length","value":9.869999999999997952},{"name":"Width","value":9.95}]

and as a double:

[{"name":"Length","value":9.8699999999999992},{"name":"Width","value":9.9499999999999993}]

I understand that a float ,double or decimal isn't super precise but what I don't understand is why the output window shows the correct values when using float until I pass through the JSONEncoder. Im not really sure how to get around this one, any suggestions would be greatly appreciated.

Asked By: David Wood
||
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles