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.
Even easier:
NSNumber *someNumber = @(1234567890);
NSString *modelNumberString = [NSString localizedStringWithFormat:@"%@", someNumber];
NSLog(@"Number with commas: %@", modelNumberString);
coworker just taught me this today. #amazing
There's a static method on NSNumberFormatter
that does just what you need:
int aNum = 2000000;
NSString *display = [NSNumberFormatter localizedStringFromNumber:@(aNum)
numberStyle:NSNumberFormatterDecimalStyle];
This way is a little more succinct than creating a new NSNumberFormatter
if you don't need to do any additional configuration of the formatter.