Reputation: 10433
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
Upvotes: 1
Views: 1520
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
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