At some point in your Mac, iPhone, or iPad development you may find the need to express a long number (1000000000) as a comma-separated string (1,000,000,000) to make life easier on your users. The NSNumberFormatter class is a rich tool for converting numbers to strings supporting different types of currencies and localizations. It’s also the perfect class to leverage for our comma-ing task.
First of all, the NSNumberFormatter class works on NSNumber objects, so we need to convert our number to a NSNumber if it’s not there already.
NSNumber *number = [NSNumber numberWithInt:1000000000];
NSNumber also supports floating point values (numberWithFloat) and the regular gang of other number formats.
With our NSNumber in hand, we can get on with the good stuff. NSNumberFormatter supports grouping of numeric digits into arbitrary length groups (we want groups of three) and separating the groups with arbitrary strings (we want to use a comma (@”,”) but we could use any string). Here’s the code that makes our string:
NSNumberFormatter *frmtr = [[NSNumberFormatter alloc] init];
NSString *commaString = [frmtr stringFromNumber:number];
Read more about NSNumberFormatter’s crazy tricks here. It can also do cool things like spelling out a number like 42 into forty-two and handling significant digits.