NSJSONSerialization Float value issue

I have a NSDictionary that contains a value of (float)7.60. When I use NSJSONSerialization it no longer has the correct value for the float field.


NSData *data = [NSJSONSerialization dataWithJSONObject:dictionaryData options:NSJSONWritingPrettyPrinted error:&error];


This is what the JSON looks like.


{

"CDCART#" : 1,

"CDACTN" : "File Update",

"CDORD#" : 0,

"CDPRIC" : 7.5999999046325684

}


Any help would be greatly appreciated.

The serialization has the correct value, but you interpreting it incorrectly.


Because it's JSON, the value in the output is a Double, and 7.5999999046325684 as a Double is the correct representation of 7.6 as a Float.


Any code that reads this JSON should be interpreting 7.5999999046325684 as a Double. If it converts the Double value to a Float, it will get 7.6 back again.

The receiving system (IBM) does not recognize a double. Only integers and decimals. Any other solutions? Is there a way to override the conversion to a double?

The receiving system (IBM) does not recognize a double. Only integers and decimals.


Then you should better re-design the receiving system. JSON is based on the JavaScript Object Notation, and in JavaScript, numeric values are represented in 64-bit binary floating point which is equivalent to Double. So, many JSON libraries use Double (or equivalent) for JSON numbers. (And you should remember that Float cannot represent the exact value `7.60`.)


Both sides using JSON as an interchangeable data format, should not expect JSON numbers to represent a precise number as decimal.


Use JSON strings, if you want to send precise digits to the receiving system, and update the receiving system to convert it to decimal.

I solved this. I changed the dictionary value to be a NSDecimalNumber rather than a NSNumber. NSJSONSerialization then outputed the JSON correctly.


{

"CDCART#" : 1,

"CDACTN" : "File Update",

"CDORD#" : 0,

"CDPRIC" : 7.6

}

That's a possible solution which may work only for some specific conditions. I strongly recommend you to change the receiver's API before any part of the system (Apple's framework or something other) would break the conditions.

NSJSONSerialization Float value issue
 
 
Q