RexOnRoids RexOnRoids - 3 months ago 12
Objective-C Question

How to add commas to number every 3 digits in Objective C?

If I have a number

int aNum = 2000000
how do I format this so that I can display it as the NSString 2,000,000?

Answer

Don't do your own number formatting. You will almost certainly not get all the edge cases right or correctly handle all possible locales. Use the NSNumberFormatter for formatting numeric data to a localized string representation.

You would use the NSNumberFormatter instance method -setGroupingSeparator: to set the grouping separator to @"," (or better yet [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator]; thanks @ntesler) and -setGroupingSize: to put a grouping separator every 3 digits.

Comments