Search code examples
iosobjective-ccurrencynsnumberformatter

NSNumberFormatter stringFromNumber: doesn't return a currency symbol


I have the following method on a custom UITableViewCell subclass:

- (void)setPrice:(NSNumber *)price {
  _price = price;
  NSNumberFormatter *formatter = [NSNumberFormatter new];
  formatter.formatterBehavior = NSNumberFormatterCurrencyStyle;
  formatter.currencyCode = @"USD";
  formatter.locale = [NSLocale currentLocale];
  priceLabel.text = [formatter stringFromNumber:_price];
}

priceLabel ends up displaying _price without a currency symbol ($). As far as I can tell, this shouldn't be happening. Any ideas?

Thanks!


Solution

  • See the constant NSNumberFormatterCurrencyStyle? Objective-C doesn't have type checking for enumerations, but you can see from the name that it's a related to NSNumberFormatterStyle.

    formatterBehavior takes a NSNumberFormatterBehavior, which is something like NSNumberFormatterBehaviorDefault.

    You want to set numberStyle instead:

    formatter.numberStyle = NSNumberFormatterCurrencyStyle;