Search code examples
objective-cnsstringnsnumberformatter

NSNumberFormatter unable to allow numbers to start with a 0


So I'm attempting to automatically add slashes between 2 digits when a user enters in their birthday, but for some reason when the birthday starts with a 0, the number formatter erases it and messes up the birthday. I've got my code below, could someone help me figure out how to do this? Thanks in advance!

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init] ;

[formatter setGroupingSeparator:@"/"];
[formatter setGroupingSize:2];
[formatter setUsesGroupingSeparator:YES];
[formatter setSecondaryGroupingSize:2];
NSString *num = textField.text ;
if(![num isEqualToString:@""])
{
    num= [num stringByReplacingOccurrencesOfString:@"/" withString:@""];
   NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
    textField.text=str;
}

Solution

  • What you could do is the following:

    • Check the length of the string
    • If length mod 2 == 0 then add "/"
    • Log your string

    I'm not saying this is recommended but it might help you a bit!

    - (void)controlTextDidChange:(NSNotification *)obj{
        NSString *num = [textField stringValue] ;
    
        if (num.length%2==0)
        {
            NSString *someText = [NSString stringWithFormat: @"%@/ ", num];
            num = someText;
        }
        textField.stringValue = num;
    }