Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: NSJSONSerialization floating point number issue

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?

like image 825
damo Avatar asked May 06 '14 00:05

damo


2 Answers

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.

like image 98
savanto Avatar answered Oct 25 '22 04:10

savanto


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

like image 36
Gautam Sareriya Avatar answered Oct 25 '22 04:10

Gautam Sareriya