WFT
WFT

Reputation: 277

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!

Upvotes: 1

Views: 705

Answers (2)

Steven Fisher
Steven Fisher

Reputation: 44876

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;

Upvotes: 2

rmaddy
rmaddy

Reputation: 318804

Change this:

formatter.formatterBehavior = NSNumberFormatterCurrencyStyle;

to:

[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];

Upvotes: 3

Related Questions