9

I'm using NSJSONSerialization to convert json string to NSDictionaray

the JSON string is

{"bid":88.667,"ask":88.704}

after NSJSONSerialization

{
    ask = "88.70399999999999";
    bid = "88.667";
}

Anybody know this issue?

damo
  • 849
  • 12
  • 16

2 Answers2

4

It looks like NSJSONSerialization will serialize your values as doubles despite the fact that doubles are not precise enough to represent certain values exactly. See more detail here: Does NSJSONSerialization deserialize numbers as NSDecimalNumber?

If precision is not super important, you can simply round your values, but since you're dealing with what appears to be a financial application, it would be best to turn your values into integers by multiplying by 1000, serializing those, and then converting back:

{"bid":88667,"ask":88704}

An alternative is to use strings.

Community
  • 1
  • 1
savanto
  • 4,470
  • 23
  • 40
1

Use below code to get your exact value.

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];

NSString *strNumber = [formatter stringFromNumber:[NSNumber numberWithFloat:88.70399999999999]];
NSString *strNumber = [formatter stringFromNumber:[NSNumber numberWithFloat:88.667]];

Output will be 88.7 & Output will be 88.67

Gautam Sareriya
  • 1,833
  • 19
  • 30