How to properly format currency on ios
You probably want something like this (assuming currency is a float):
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:currency]];
From your requirements to treat 52 as .52 you may need to divide by 100.0.
The nice thing about this approach is that it will respect the current locale. So, where appropriate it will format your example as "5.212,42".
Update:I was, perhaps, a little speedy in posting my example. As pointed out by Conrad Shultz below, when dealing with currency amounts, it would be preferable to store the quantities as NSDecimalNumber
s. This will greatly reduce headaches with rounding errors. If you do this the above code snippet becomes (assuming currency is a NSDecimalNumber*
):
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];NSString *numberAsString = [numberFormatter stringFromNumber:currency];
I use this code. This work for me
1) Add UITextField Delegate to header file
2) Add this code (ARC enabled)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {NSString *cleanCentString = [[textField.text componentsSeparatedByCharactersInSet: [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];// Parse final integer valueNSInteger centAmount = cleanCentString.integerValue;// Check the user inputif (string.length > 0){ // Digit added centAmount = centAmount * 10 + string.integerValue;}else{ // Digit deleted centAmount = centAmount / 10;}// Update call amount valueNSNumber *amount = [[NSNumber alloc] initWithFloat:(float)centAmount / 100.0f];// Write amount with currency symbols to the textfieldNSNumberFormatter *_currencyFormatter = [[NSNumberFormatter alloc] init];[_currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];[_currencyFormatter setCurrencyCode:@"USD"];[_currencyFormatter setNegativeFormat:@"-ยค#,##0.00"];textField.text = [_currencyFormatter stringFromNumber:amount];return NO; }