0

When I convert JSON data which contains double value like 4999.99 to JSON String it outputs with different value with multiple decimal points like 4999.9899999999998

I used the following code for JSON NSJSONSerialization and encoding.

jsonData = [NSJSONSerialization dataWithJSONObject:dataDic options:1 error:&error];

jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 

In dataDic there has key/value pairs like @amount: (double)4999.99

but in jsonString contains "amount" : 4999.9899999999998, instead of 4999.99

Please help me to get jsonstring to as dataDic values correctly.

Malisha De Silva
  • 393
  • 2
  • 10
  • 1
    I'm sorry, but it's correct. Most accurate representation of the `4999.99` is `4.9999899999999997817212715745E3` (= `4999.9899999999997817212715745`). Read [Floating-point arithmetic](https://en.wikipedia.org/wiki/Floating-point_arithmetic) or use another data type for you value. – zrzka Jul 20 '20 at 15:12
  • I need to get only 4999.99 from jsonString variable here I used. (same exact value which I pass through dataDic, not most accurate representation). – Malisha De Silva Jul 21 '20 at 05:24
  • 2
    It seems that you don't understand how floating point works. When you write `4999.99` in the code, `4999.99` is not stored in the variable, but sign, exponent and mantissa are stored in all these 64 bits and they represent some value which is as close as possible to your initial value. Then when you read this number back, you'll get `4999.9899...`. [Check this converter for example](https://www.binaryconvert.com/result_double.html?decimal=052057057057046057057) or [How to represent currency or money in C](https://stackoverflow.com/questions/32212213/how-to-represent-currency-or-money-in-c). – zrzka Jul 21 '20 at 08:21
  • Thank you @zrzka . This answer helped me. I will try **NSDecimalNumber** class in objective c – Malisha De Silva Jul 22 '20 at 11:36

0 Answers0