miah
miah

Reputation: 10433

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!)

Upvotes: 1

Views: 1520

Answers (2)

David Rönnqvist
David Rönnqvist

Reputation: 56625

The best for currency would be the NSNumberFormatterCurrencyStyle

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

Upvotes: 6

Wain
Wain

Reputation: 119031

What you have is fine.

You could use [NSDecimalNumber decimalNumberWithString:price] to deal with the source price a little better if it isn't an integer.

You could use [formatter setCurrencySymbol:@"$"] to deal with the symbol instead of stringWithFormat.

These changes would make the implementation you have more robust and elegant.

Upvotes: 1

Related Questions