Swift encodes double 0.1 to JSON as 0.10000000000000001
Asked Answered
L

1

5

After having a double variable initialized with 0.1 value and encoding it to JSON via SwiftyJSON I receive 0.10000000000000001 in JSON structure.

I'm aware of precision memory storage differences between float/double and integer but still I didn't found a quick fix for such situation besides using sprintf formatting like %.2f - I don't want to result with putting a string into json structure.

Any quick & easy solution to this will be appreciated.

I expect to have 0.1 value in JSON. If double value is 10 I expect value 10 in JSON. But how to avoid such precision-rounding errors during json encoding operation?

Libbielibbna answered 27/6, 2019 at 6:58 Comment(8)
0.10000000000000001 is 0.1. It's not Swift that does this, it's the fact that the two numbers are identical.Print
I have realized this and I understand that from the computing point of view it is indeed the same. But still I want to avoid such situation because of visual manners. Both platforms (iOS & Android) are saving 0.1 value into JSON. But in reality Android saves 0.1 but iOS saves 0.10000000000000001. I would like to remove this distinctionLibbielibbna
That's floating point numbers, that's how they work. You can always truncate that number to a specific digit if you want.Armil
Truncation will not help me here. See this: #35946999Libbielibbna
What about formatting and storing it as a string instead?Melancholia
As I wrote in the question: storing as string is a no-go for my case. Another system which parses this JSON expects a number.Libbielibbna
Use NSNumber or Decimal insteadLakitalaks
https://mcmap.net/q/73421/-rounding-a-double-value-to-x-number-of-decimal-places-in-swift this may be helpful.Undertook
S
10

Late to the party but for others with the same issue - defining your fields as Decimal instead of Float or Double is the way to go.

If you're working with Floats or Doubles in your app just use e.g.:

let obj = MyObj(myField: Decimal(myFloat))

Then when you serialise MyObj to JSON you should see:

{
  "myfield": 0.1
}

instead of 0.10000000000000001

Suchta answered 11/2, 2021 at 17:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.