Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 508
RexOnRoids Avatar asked Feb 10 '10 01:02

RexOnRoids


People also ask

How do you add a comma to every three digit number in Python?

def comma(num): '''Add comma to every 3rd digit. Takes int or float and returns string. ''' if type(num) == int: return '{:,}'. format(num) elif type(num) == float: return '{:,.


2 Answers

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.

like image 98
Nik Avatar answered Sep 24 '22 13:09

Nik


Don't do your own number formatting. You will almost certainly not get all the edge cases right or correctly handle all possible locales. Use the NSNumberFormatter for formatting numeric data to a localized string representation.

You would use the NSNumberFormatter instance method -setGroupingSeparator: to set the grouping separator to @"," (or better yet [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator]; thanks @ntesler) and -setGroupingSize: to put a grouping separator every 3 digits.

like image 33
Barry Wark Avatar answered Sep 25 '22 13:09

Barry Wark