2

Float values are getting changed after parsing with JSONKit. The problem occurs after calling objectFromJSONString or mutableObjectFromJSONString.

The JSON response is fine before this method is triggered in JSONKit.m:

static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection)

Original response:

"value":"1002.65"

Response after calling objectFromJSONString:

"value":"1002.6500000001" or sometimes "value":"1002.649999999 "

Thanks.

jszumski
  • 7,430
  • 11
  • 40
  • 53
Warrior
  • 39,156
  • 44
  • 139
  • 214

2 Answers2

3

This is not an issue.

The value 1002.65 can not be represented exactly using a IEEE 754 floating point number. Floating-point numbers are converted to their decimal representation using the printf format conversion specifier %.17g. 

From the Docs:

The C double primitive type, or IEEE 754 Double 64-bit floating-point, is used to represent floating-point JSON Number values. JSON that contains floating-point Number values that can not be represented as a double (i.e., due to over or underflow) will fail to parse and optionally return a NSError object. The function strtod() is used to perform the conversion. Note that the JSON standard does not allow for infinities or NaN (Not a Number). The conversion and manipulation of floating-point values is non-trivial. Unfortunately, RFC 4627 is silent on how such details should be handled. You should not depend on or expect that when a floating-point value is round tripped that it will have the same textual representation or even compare equal. This is true even when JSONKit is used as both the parser and creator of the JSON, let alone when transferring JSON between different systems and implementations.

Source: See this thread https://github.com/johnezang/JSONKit/issues/110

Solution: You can specify a precision, while converting float to string for output. NSNumberFormatter will be a better choice or use some printf solutions like in the previous answer.

DD_
  • 7,230
  • 11
  • 38
  • 59
0

use float fixed point representation like,

 NSLog(@"value = %.2f",floatvalue); 

now it will show value = 1002.65

NewStack
  • 990
  • 8
  • 19