3

How to set up the display to show commas: 24,532,664 as opposed to 24532664?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
jdl
  • 6,151
  • 19
  • 83
  • 132

3 Answers3

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!!!

Community
  • 1
  • 1
Tom
  • 2,360
  • 21
  • 15