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?
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 '{:,.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With