Search code examples
iosuitextfieldnsnumber

Grouping separator while changing value in UITextfield


In order to edit a group-separated number in an UITextField the grouping separator needs to get switched of while editing. Otherwise the returned value (stored as NSNumber value) is (NULL) due to missplaced gouping separators (see the picture and imagine the number is going to be extended by another digit e.g. to "50.0000").

How can I achieve this?

enter image description here

Right now the value is handled in -(void) textFieldDidEndEditing:(UITextField *)textField method.

(My locale is German so the "." is the grouping separator not the decimal separator!) But I try to get the code working for all regions.


Solution

  • Try with this solution :

    -(void) textFieldDidEndEditing:(UITextField *)textField {
    
     NSString *stringWithoutDots = [textField.text stringByReplacingOccurrencesOfString:@"." withString:@""]; //remove dots
    
    int number = [stringWithoutDots intValue]; //convert into int
    
    NSNumberFormatter *formatter = [NSNumberFormatter new];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; // this line is important!
    
    NSString *formatted = [formatter stringFromNumber:[NSNumber numberWithInteger:number]];
    
    
    
    }
    

    I hope this help you. Kevin MACHADO