Format currency with UITextField

375 views Asked by At

I have a UITextField that the user will enter an amount of money. I want to set it so it will show the users current currency. I could do the following:

- (void)textFieldDidEndEditing:(UITextField *)textField {

    NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [currencyFormatter setLocale:[NSLocale currentLocale]];
    [currencyFormatter setMaximumFractionDigits:2];
    [currencyFormatter setMinimumFractionDigits:2];
    [currencyFormatter setAlwaysShowsDecimalSeparator:YES];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    NSNumber *someAmount = [NSNumber numberWithDouble:[textField.text doubleValue]];
    NSString *string = [currencyFormatter stringFromNumber:someAmount];

    textField.text = string;
}

That works. But I want it to show on startup, and while the user is typing the amount. The above code only works when the user is finished with that textField. How can I make the code in that method to show on startup and while the user is entering numbers.

I tried to change the method to shouldChangeTextInRange, but it gives a weird effect.

1

There are 1 answers

0
Eluss On

If you are using ReactiveCocoa you can try doing this.

[textField.rac_textSignal subscribeNext:^(NSString *text) {
    if (text.length < 4) text = @"0.00";

    //set currency style
    NSNumberFormatter *currencyFormatter = [NSNumberFormatter new];
    currencyFormatter.numberStyle = NSNumberFormatterCurrencyStyle;

    //leave only decimals (we want to get rid of any unwanted characters)

    NSString *decimals = [[text componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];

    //insert decimal separator
    NSMutableString *mutableString = [NSMutableString stringWithString:decimals];
    [mutableString insertString:currencyFormatter.decimalSeparator atIndex:mutableString.length - currencyFormatter.minimumFractionDigits];

    //I add currency symbol so that formatter recognizes decimal separator while formatting to NSNumber
    NSString *result = [currencyFormatter.currencySymbol stringByAppendingString:mutableString];

    NSNumber *formattedNumber = [currencyFormatter numberFromString:result];
    NSString *formattedText = [currencyFormatter stringFromNumber:formattedNumber];

    //saving cursors position 
    UITextRange *position = textField.selectedTextRange;

    textField.text = formattedText;

    //reassigning cursor position (Its not working properly due to commas etc.)
    textField.selectedTextRange = position;
}];

It's not perfect, but maybe this can help you a bit in finding correct solution.