Question

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.

Was it helpful?

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]);

OTHER TIPS

100,00096 isn't correct...

Do you mean one of these?

[[self.currencyFormatter numberFromString:@"£10000096"] integerValue]
[[self.currencyFormatter numberFromString:@"£100,000.96"] integerValue]
[[self.currencyFormatter numberFromString:@"£100000.96"] integerValue]
[[self.currencyFormatter numberFromString:@"£10,000,096"] integerValue]

My final code for the reference. The number with currency symbol also an invalid! Following takes care of everything.

    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:[NSString stringWithFormat:@"%@%@", self.currencyFormatter.groupingSeparator, self.currencyFormatter.currencySymbol]];
    self.amountTextField.text = [[self.amountTextField.text componentsSeparatedByCharactersInSet:doNotWant] componentsJoinedByString:@""];
    self.amountTextField.text = [NSString stringWithFormat:@"£%@", self.amountTextField.text];
    NSUInteger amount = [[self.currencyFormatter numberFromString:self.amountTextField.text] integerValue];
    self.amountTextField.text = [self.currencyFormatter stringFromNumber:[NSNumber numberWithInteger:amount]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top