Since you want the UITextField to have a maximum of 7 integer digits, you’ll need to validate every modification, and prevent any that result in a number with > 7 integer digits. The simplest way I know to do that is the UITextFieldDelegate method shouldChangeCharactersInRange
:
- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {
NSString* modifiedFieldText = [textField.text stringByReplacingCharactersInRange:range withString:string] ;
// Remove all characters except for the digits 0 - 9.
NSString* filteredToDigits = [modifiedFieldText stringByFilteringCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]] ;
// Change textField's text only if the result is <= 9 digits (7 integer digits and 2 fraction digits).
if ( filteredToDigits.length <= 9 ) {
// If you'd rather this method didn't change textField's text and only determined whether or not the change should proceed, you can move this code block into a method triggered by textField's Editing Changed, replacing this block with "return YES". You'll need to once again filter textField's text to only the characters 0 - 9.
NSNumberFormatter* numberFormatter = [NSNumberFormatter new] ;
numberFormatter.numberStyle = NSNumberFormatterCurrencyStyle ;
NSNumber* asNumber = @( filteredToDigits.doubleValue / 100.0 ) ;
textField.text = [numberFormatter stringFromNumber:asNumber] ;
}
// This method just changed textField's text based on the user's input, so iOS should not also change textField's text.
return NO ;
}
I used an NSString category to change @”$12,345.67″ into @”1234567″.
NSString+Filter.m
- (NSString*) stringByRemovingCharactersInSet:(NSCharacterSet*)charactersToRemove {
return [[self componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""] ;
}
- (NSString*) stringByFilteringCharactersInSet:(NSCharacterSet*)charactersToKeep {
NSCharacterSet* charactersToRemove = [charactersToKeep invertedSet] ;
return [self stringByRemovingCharactersInSet:charactersToRemove] ;
}
2
solved How to display Comma separated and Fractional values in UITextfiled? [closed]