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.