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

RexOnRoids picture RexOnRoids · Feb 10, 2010 · Viewed 51k times · Source

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

Nik picture Nik · Dec 14, 2011

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.