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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With