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

Objective CNsstring

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - 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.

Solution 2 - Objective C

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.

Solution 3 - Objective C

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.

Solution 4 - Objective C

Even easier:

NSNumber *someNumber = @(1234567890);
NSString *modelNumberString = [NSString localizedStringWithFormat:@"%@", someNumber];
NSLog(@"Number with commas: %@", modelNumberString);
coworker just taught me this today. #amazing

Solution 5 - Objective C

Think some as i will get this post looking for sample. So if you are working with number make attention on next params:

setNumberStyle:NSNumberFormatterCurrencyStyle // if you are working with currency

It could be also

setNumberStyle:NSNumberFormatterDecimalStyle

All code is For ARC.

If you are working with Integer and need to get result such as 200,000

int value = 200000;
NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString * newString =  [formatter stringFromNumber:[NSNumber numberWithInteger:value]];

If you are working with Float and need to get result such as 200,000.00

float value = 200000;
NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2]; // Set this if you need 2 digits
NSString * newString =  [formatter stringFromNumber:[NSNumber numberWithFloat:value]];

EDIT

To have ability to use different digital separators use NSLocale. Add to code where NSLocale is specified on Locale Identifier:

[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"de_DE"]];

or use current local:

[formatter setLocale:[NSLocale currentLocale]];

Solution 6 - Objective C

Swift version

let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.maximumFractionDigits = decimalPlaces
let result = formatter.stringFromNumber(NSNumber(double: 8.0))

By http://ios.eezytutorials.com

Solution 7 - Objective C

An easy solution could be this. My answer is almost same like @Nazir's answer but with a small trick.

double current_balance = 2000000.00;

NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
//[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];  //if you want for currency with $ sign
[formatter setMinimumFractionDigits:2]; // Set this if you need 2 digits
[formatter setMaximumFractionDigits:2]; // Set this if you need 2 digits
NSString * currency_format =  [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithDouble:current_balance]]];

Solution 8 - Objective C

For Swift 4.0

let formatter = NumberFormatter()
        
formatter.numberStyle = .decimal
        
formatter.minimumFractionDigits = 2
     
formatter.maximumFractionDigits = 2
        
let result = formatter.string(from: NSNumber(value: 123456))

Solution 9 - Objective C

For those who need to do it with strings of numbers and not just integers (I.e. Big Numbers) I made the following macro:

#define addCommas(__string) (\
(^NSString *(void){\
NSString *__numberString = __string;\
NSString *__integerPortion = __numberString;\
NSString *__decimalPortion = @"";\
if ([__string containsString:@"."]) {\
__integerPortion = [__numberString componentsSeparatedByString:@"."][0];\
__decimalPortion = st(@".%@", [__numberString componentsSeparatedByString:@"."][1]);\
}\
int __i = (int)__integerPortion.length-3;\
while (__i > 0) {\
__integerPortion = st(@"%@,%@", substringInRange(__integerPortion, 0, __i), substringInRange(__integerPortion, __i, (int)__integerPortion.length));\
__i -= 3;\
}\
__numberString = st(@"%@%@", __integerPortion, __decimalPortion);\
return __numberString;\
})()\
)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRexOnRoidsView Question on Stackoverflow
Solution 1 - Objective CNikView Answer on Stackoverflow
Solution 2 - Objective CBarry WarkView Answer on Stackoverflow
Solution 3 - Objective CPhil CalvinView Answer on Stackoverflow
Solution 4 - Objective CyujeanView Answer on Stackoverflow
Solution 5 - Objective CNazirView Answer on Stackoverflow
Solution 6 - Objective CRaj iOSView Answer on Stackoverflow
Solution 7 - Objective CJulfikarView Answer on Stackoverflow
Solution 8 - Objective CSandip Patel - SMView Answer on Stackoverflow
Solution 9 - Objective CAlbert RenshawView Answer on Stackoverflow