I want to have commas dynamically added to my numeric UITextField entry while the user is typing.
For example: 123,456 and 12,345,678
EDIT See Lindsey Scott's answer for an updated, correct version.
This is based on Lindsey Scott's previous answer, but updated to account for 0's entered after the decimal:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == _questionPoolNameTextField) {
return YES;
}
//For 0's after the decimal point:
if ([string isEqualToString:@"0"] && (0 <= (int)[textField.text rangeOfString:@"."].location)) {
if ([textField.text rangeOfString:@"."].location < range.location) {
return YES;
}
}
// First check whether the replacement string's numeric...
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
bool isNumeric = [string isEqualToString:filtered];
// Then if the replacement string's numeric, or if it's
// a backspace, or if it's a decimal point and the text
// field doesn't already contain a decimal point,
// reformat the new complete number using
// NSNumberFormatterDecimalStyle
if (isNumeric ||
[string isEqualToString:@""] ||
([string isEqualToString:@"."] &&
[textField.text rangeOfString:@"."].location == NSNotFound)) {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setGroupingSeparator:@","];
[numberFormatter setGroupingSize:3];
[numberFormatter setDecimalSeparator:@"."];
[numberFormatter setMaximumFractionDigits:20];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
// Combine the new text with the old; then remove any
// commas from the textField before formatting
NSString *combinedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *numberWithoutCommas = [combinedText stringByReplacingOccurrencesOfString:@"," withString:@""];
NSNumber *number = [numberFormatter numberFromString:numberWithoutCommas];
NSString *formattedString = [numberFormatter stringFromNumber:number];
// If the last entry was a decimal at the end of the
// re-add it here because the formatter will naturally
// remove it.
if ([string isEqualToString:@"."] &&
range.location == textField.text.length) {
formattedString = [formattedString stringByAppendingString:@"."];
}
textField.text = formattedString;
}
// Return no, because either the replacement string is not
// valid or it is and the textfield has already been updated
// accordingly
return NO;
}