Viet Nguyen
Viet Nguyen

Reputation: 2373

Objective C textfield formatter commas every two number

I would like inserting commas to every two number in uitextfield while typing but my code isn't work and I don't know where is the mistake I've made.

Idea: when user type 23456789 then format it to 23,45,67,89 while they're typing.

Here is my code:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init] ;
if([string length]==0)
{
    [formatter setGroupingSeparator:@"-"];
    [formatter setGroupingSize:4];
    [formatter setUsesGroupingSeparator:YES];
    [formatter setSecondaryGroupingSize:2];
    NSString *num = textField.text ;
    num= [num stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
    textField.text=str;
    NSLog(@"%@",str);
    return YES;
}
else {
    [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;
    }

    //NSLog(@"%@",str);
    return YES;
}

When I type, number always show 3 char before insert commas like this 1,23,44,567

Any idea?

Upvotes: 0

Views: 97

Answers (1)

Curmudgeonlybumbly
Curmudgeonlybumbly

Reputation: 639

Well, it appears as if there's a bug in setGroupingSize, and to work around it you should change

[formatter setGroupingSize:2] 

to

[formatter setGroupingSize:1]

Which solves the immediate problem. But there's some other issues in your code. Do you want to use NumberWithDouble and doubleValue, or should you be using integers? How are negative number handled? What is the range of valid inputs? What happens if the user tries to edit the middle of the text? Why is there a different formatter when string length is 0? Is this really the best way to collect input from the user

Upvotes: 1

Related Questions