Search code examples
iostextfieldnsnumberformatter

iOS: NSNumberFormatter doesn't convert string back to NSNumber


I am using following NSNumberFormatter to add commas and symbol in the currency value.

self.currencyFormatter = [NSNumberFormatter new];
self.currencyFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
self.currencyFormatter.currencySymbol = @"£";
self.currencyFormatter.currencyCode = @"GBP";
self.currencyFormatter.roundingMode = NSNumberFormatterRoundHalfUp;
self.currencyFormatter.maximumFractionDigits = 0;

Usage:

self.principleAmountTextField.text = [self.currencyFormatter stringFromNumber:[NSNumber numberWithInteger:100000]];

This displays £100,000 as expected. Now if I insert two more digits (text becomes £100,00096) in textfield and try to convert string to Integer I get 0! Basically following line returns 0. I have no idea how to deal with this issue.

NSLog(@"%d", [[self.currencyFormatter numberFromString:@"£100,00096"] integerValue]);

FYI I have custom inputview to textfield which just allows numbers to enter into textfield. In Did Edit End even I format number and display with comma.


Solution

  • You need to remove the commas for this to work, you can still show them in your text field but you should strip them out before you pass the string to the formatter. Something like this:

    NSString *userInput = @"£100,00096";    
    userInput = [userInput stringByReplacingOccurrencesOfString:@"," withString:@""];
    NSLog(@"%ld", (long)[[currencyFormatter numberFromString:userInput] integerValue]);