How to set up the display to show commas: 24,532,664 as opposed to 24532664?
Asked
Active
Viewed 332 times
3 Answers
8
Using NSNumberFormatter.
Listing 1
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *myNumber = [NSNumber numberWithInteger:122344];
NSString *formattedNumberString = [numberFormatter stringFromNumber:myNumber];
[numberFormatter release]; // if you aren't using ARC.
NSLog(@"formattedNumberString: %@", formattedNumberString);
// Output for locale en_US: "formattedNumberString: formattedNumberString: 122,344"

DrummerB
- 39,814
- 12
- 105
- 142
3
You may use -[NSString initWithFormat:locale:]
.
NSLocale *locale = [NSLocale currentLocale]; // always use the user's locale
NSString *string = [[NSString alloc] initWithFormat:@"%d" locale:locale, 24532664];
If the commas are mandatory, you may choose a specific locale (en_US
), in order to always get the same result. But that's not a good idea if the string is meant to be displayed to the user.
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

Nicolas Bachschmidt
- 6,475
- 2
- 26
- 36
1
You need to use NSNumberFormatter for this.
E.g. Formatting a number to show commas and/or dollar sign
Don't forget to clean up after!!!