I am trying to convert strings into numbers using NSNumberFormatter. In my application, input strings with more than 2 digits after the decimal point are not valid, i.e., @"3.1" and @"3.14" are valid inputs, but @"3.141" is not.
The documentation for NSNumberFormatter says that setMaximumFractionDigits: “[s]ets the maximum number of digits after the decimal separator allowed as input by the receiver.”
So, I was surprised when this code:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.maximumFractionDigits = 2;
NSNumber *number = [numberFormatter numberFromString:@"3.141"];
NSLog(@"%@", number);
accepted @"3.141" and gave me the following output:
3.141
I was expecting the conversion of @"3.141" to fail (and return nil) because it has more than the maximum number of digits allowed after the decimal separator.
Obviously I’m not understanding something basic here. Does NSNumberFormatter not use maximumFractionDigits as part of validating string input?
Guessing from the lack of other answers or any indication of this in the official documentation: No,
NSNumberFormatterdoesn’t support comprehensive validation when parsing numbers, andmaximumFractionDigitsis only relevant when formatting numbers. This seems to be consistent with withsscanf,strtofand such.