Realtime formatting with NSNumberFormatter in a UITextfield

cocoa-touch, iphone, objective-c

Solution

Here's the idea...

Store the string value, append to it, then use that for the operation.

Define an NSMutableString in the .h file

NSMutableString *storedValue;
@property (nonatomic, retain) NSMutableString *storedValue;

Synthesize it.

Then do this...

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   if ([textField tag] == amountTag)
    {
    [storedValue appendString:string];
    NSString *newAmount = [self formatCurrencyValue:([storedValue doubleValue]/100)];

    [textField setText:[NSString stringWithFormat:@"%@",newAmount]];
    return NO;
    }

    //Returning yes allows the entered chars to be processed
    return YES;
}

Problem

I have UITextfield where a user can put in a dollar amount, I would like the textfield always to be formatted with two decimals ($ .##). The formatting has to be maintained all the time. But i'm stuck on how to append the entered numbers to existing ones in the textfield ? ``` //This delegate is called everytime a character is inserted in an UITextfield. - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ([textField tag] == amountTag) { NSString *amount = string; //How do I append the already entered numbers in the textfield to the new entered values ? //?? //Get new formatted value NSString *newAmount = [self formatCurrencyValue:[amount doubleValue]]; [textField setText:[NSString stringWithFormat:@"%@",newAmount]]; return NO; } //Returning yes allows the entered chars to be processed return YES; } -(NSString*) formatCurrencyValue:(double)value { NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init]autorelease]; [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [numberFormatter setCurrencySymbol:@"$"]; [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; NSNumber *c = [NSNumber numberWithFloat:value]; return [numberFormatter stringFromNumber:c]; } ```

Original source