I have this sample code:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSString *numberString = @"9.2";
NSNumber *number = [formatter numberFromString:numberString];
NSLog(@"String: %@, Number: %@", numberString, number);
The printed result is:
String: 9.2, Number: 9.199999999999999
I don’t understand why this would happen. Am I missing a setting?
According to this reference, an
NSNumbercan store any ordinary C numeric type. Since this is obtained by parsing a non-integer, the two types to choose from arefloatanddouble, and by the displayed value, the chosen representation isdouble.Since decimal fractions like 9.2 aren’t exactly representable as
doubles, you get the closest representable number. That is displayed to default precision, which is about 16 decimal places.