Skip to content

JSONEncoder floating point behavior differs between Darwin and non-Darwin implementation #4704

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
fumoboy007 opened this issue Feb 17, 2023 · 6 comments

Comments

@fumoboy007
Copy link
Contributor

fumoboy007 commented Feb 17, 2023

The floating point behavior of JSONEncoder differs between the Darwin and non-Darwin implementation of Foundation.

Test Case

import Foundation

let array = [
  1.1
]

let jsonEncoder = JSONEncoder()

let jsonBytes = try! jsonEncoder.encode(array)
let jsonString = String(decoding: jsonBytes, as: UTF8.self)

print(jsonString)

Darwin Output

[1.1000000000000001]

Non-Darwin Output

[1.1]
@fumoboy007
Copy link
Contributor Author

If I had a vote, I would vote for the non-Darwin behavior, which is neater.

One could argue the Darwin behavior is more precise but I think that argument misses the fact that floating point is imprecise to begin with… one cannot tell whether the floating point value actually represents 1.1 or 1.1000000000000001.

So, in the absence of precision, I would suggest choosing the neater one.

@fumoboy007
Copy link
Contributor Author

This Swift commit changed Swift’s floating point formatting logic, mentioning the following:

This format is also ideal for logging, debugging, and other general display. In particular, the shortness guarantee avoids the confusion of unnecessary additional digits, so that the result of 1.0 / 10.0 consistently displays as 0.1 instead of 0.100000000000000000001.

@fumoboy007
Copy link
Contributor Author

Filed FB11996256 requesting that the Darwin implementation be updated to match the non-Darwin implementation.

@21DCS059
Copy link

i want to contribute in this project please assign it to me.

@fumoboy007
Copy link
Contributor Author

@21DCS059 See above comment. There shouldn’t be any action needed in this repository. Instead, I filed FB11996256, which requests that Apple modify their closed-source version of Foundation.

@parkera
Copy link
Contributor

parkera commented Jul 5, 2024

This produces [1.1] using swift-foundation's JSONEncoder. See also #5001.

@parkera parkera closed this as completed Jul 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants