Add Comma Separators to Numbers

Seems a common question, how can I format a number such as 123456 to look like 123,456? The NSNumberFormatter makes this quite easy.

NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
double d = 234567.89;
int i = 1234567890;
NSString *strFloat = [formatter stringFromNumber:[NSNumber numberWithDouble:d]];
NSString *strInt = [formatter stringFromNumber:[NSNumber numberWithInt:i]];
NSLog(@"Float: %@", strFloat);
NSLog(@"Int: %@", strInt);

The output would look like this:

Float: 234,567.89
Int: 1,234,567,890

Adding Comma Separator to Currency

If you are working with currency, change the number style as shown:

NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
double d2 = 234567.89;
NSString *strCurrency = [currencyFormatter stringFromNumber:[NSNumber numberWithDouble:d2]]; 
NSLog(@"%@", strCurrency);

The output would look like this:


If you have a code example that is different from above, please share in a comment below.

Also, one area that I didn’t consider in these examples is localization. Any code examples regarding this are also welcome.