20

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
David Wood
  • 1,319
  • 2
  • 12
  • 15
  • Possible duplicate of [Why are doubles printed differently in dictionaries?](https://stackoverflow.com/questions/40959254/why-are-doubles-printed-differently-in-dictionaries) – printing a *dictionary* calls `debugDescription` on its floating point entries, and that prints the values with a higher precision. – Martin R Sep 18 '17 at 07:26
  • 1
    Please use Decimal instead of Float. But Codable in Swift 4 still is incorrect in some cases. Hope Apple fix it soon. You can check the issue here: https://bugs.swift.org/browse/SR-5278?focusedCommentId=28264&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-28264 – Duan Nguyen Mar 02 '18 at 03:43
  • 3
    Damn floating points!!! – funct7 Oct 14 '18 at 14:02
  • 4
    Looks like this issue still exists! – Usuf Feb 07 '19 at 17:01
  • 3
    Still exists as of March 2020! – ZeMoon Mar 12 '20 at 09:12
  • It does. I'm having a damn problem with that. – JBarros35 May 28 '20 at 17:29
  • https://stackoverflow.com/a/62997953/2303865 – Leo Dabus Jul 20 '20 at 17:10
  • Still exists as November 2020! – aturan23 Nov 06 '20 at 09:51

0 Answers0