Adding commas to numbers on iOS

Recently I ran into another problem in one of our care apps. We had some user entries in our journals. Some of these numbers were in few thousands. (Such as number of steps, calories etc.). Initially we used to display them as it is. But later we figured that it is not really a good user experience to show just numbers without introducing any commas in them which obviously increases readability of sufficiently large number.

So here we go. Thanks to StackOverflow post which showed how to introduce commas to regular number (Be it CGFloat, double, NSInteger or similar number). We are going to use NSNumberFormatter class to achieve desired effect.

As taken from the blog post,


NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber* inputNumber = [NSNumber numberWithInteger:100000]
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString* formattedNumber = [numberFormatter stringFromNumber:inputNumber];
// Output formattedNumber = 1,00,000

It's as simple as this. I didn't know Apple provides such inbuilt function to achieve this effect. Thank god I didn't begin with my custom method.

Jayesh Kawli

I am a web and mobile developer working at Wayfair in Boston, MA. I come to learn so many things during course of life and I write about things which helped me and feel like they can help others too.

Subscribe to Fresh Beginning

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!