Question

I have two UITextFields in my app and the app has to do with currency. I am attempting to have it formatted correctly with the $ at the beginning and the decimal where it should. Like I said. I have been unable to find a noob answer to my question.

Was it helpful?

Solution

Whats happening here is you're adding an observer that tells us when the user is finished editing. Once that happens our formatCurrency method does the work of updating the look of the textfield. The changes take full affect once the number field resigns its first responder status.

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(formatCurrency)
                                             name:UITextFieldTextDidEndEditingNotification
                                               object:self.numberField];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.numberField resignFirstResponder];
}

-(void)formatCurrency {
    NSString *currentValue = self.numberField.text;
    long long cur = [currentValue longLongValue];
    NSNumber *curNum = @(cur);
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    self.numberField.text = [NSNumberFormatter localizedStringFromNumber:curNum
                                          numberStyle:NSNumberFormatterCurrencyStyle];
}

OTHER TIPS

UILabel *price; 
NSString *dollarSign = "$";//Just use whatever currency symbol you need


price.text = [dollarSign stringByAppendingString:[NSString stringWithFormat:@"%.2f", priceVariable]];

This will print in the format $xxx.xx

I wrote a UITextField subclass to handle currency formatting, available here:

https://github.com/TomSwift/TSCurrencyTextField

It formats the currency amount as the user types, ATM-style. The user is restricted from entering anything but digits. The control uses a NSNumberFormatter (currency-style!) internally and you can tweak that if you like, to adjust the currency symbol ($), decimal places, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top