Search code examples
iosnsnumberformatter

What is the best way to format string representation of number in iOS


In the iOS app I am writing, I receive a json object with a string representation of a price, something like this:

{
  "price":"20000"
}

And I'd like to format it with commas for ease of readability, and I have found a way, but I feel like it is a crazy clunky (I probably just didn't use the right terms in google).

 NSNumberFormatter *formatter = [NSNumberFormatter new];
 [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
 NSString price = [NSString stringWithFormat:@"$%@", [formatter stringFromNumber:[NSNumber numberWithInteger:[price intValue]]]];

It seems overly complex to me that to get the proper formatting I have to

  1. Convert the NSString to an int.
  2. Convert the int to a NSNumber.
  3. Convert the NSNumber to an NSString.
  4. Create a new string with the proper format (@david/@wain showed me how to drop this step!)

Solution

  • The best for currency would be the NSNumberFormatterCurrencyStyle

    NSNumberFormatter *formatter = [NSNumberFormatter new];
    [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *price = @([priceTextFromJSON doubleValue]);
    NSString *priceText = [formatter stringFromNumber:price];