How to add commas to number every 3 digits in Objective C?
Use NSNumberFormatter
.
Specifically:
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle]; // this line is important!
NSString *formatted = [formatter stringFromNumber:[NSNumber numberWithInteger:2000000]];
[formatter release];
By default NSNumberFormatter
uses the current locale so the grouping separators are set to their correct values by default. The key thing is to remember to set a number style.
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.