Objective-C: NSYSONSerialization floating point number

I am using NSJSONSerialization to convert json string to NSDictionaray

json string

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

after NSJSONSerialization

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

Does anyone know this problem?

+7
nsjsonserialization
source share
2 answers

It looks like NSJSONSerialization will serialize your values โ€‹โ€‹as doubles, even though the doubles are not accurate enough to represent specific values โ€‹โ€‹exactly. Read more here: Does NSJSONSerialization perform deserialization of numbers as NSDecimalNumber?

If accuracy is not very important, you can simply round off your values, but since you are dealing with what seems like a financial application, it would be better to turn your values โ€‹โ€‹into integers by multiplying them by 1000, and then back:

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

An alternative is to use strings.

+4
source share

Use the code below to get the 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]]; 

The output will be 88.7 & The output will be 88.67

+1
source share

All Articles