Heps
Heps

Reputation: 995

Swift encodes double 0.1 to JSON as 0.10000000000000001

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?

Upvotes: 5

Views: 3301

Answers (1)

norders
norders

Reputation: 1252

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

Upvotes: 10

Related Questions