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?

Heps
  • 945
  • 9
  • 24
  • 0.10000000000000001 ***is*** 0.1. It's not Swift that does this, it's the fact that the two numbers are identical. – MSalters Jun 27 '19 at 07:01
  • 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 distinction – Heps Jun 27 '19 at 07:05
  • That's floating point numbers, that's how they work. You can always truncate that number to a specific digit if you want. – philoez98 Jun 27 '19 at 07:05
  • Truncation will not help me here. See this: https://stackoverflow.com/questions/35946499/how-to-truncate-decimals-to-x-places-in-swift#comment79033256_35946921 – Heps Jun 27 '19 at 07:07
  • What about formatting and storing it as a string instead? – Sweeper Jun 27 '19 at 07:15
  • 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. – Heps Jun 27 '19 at 07:22
  • Use `NSNumber` or `Decimal` instead – Malik Jun 27 '19 at 07:53
  • https://stackoverflow.com/a/38036978/5850840 this may be helpful. – atalayasa Jun 27 '19 at 08:56

1 Answers1

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

norders
  • 1,160
  • 9
  • 13