views:

227

answers:

3

I can't seem to find an easy way to do it. The exact thing I need is:

[NSString stringWithFormat:@"%d doodads", n];

Where n is an int. So for 1234 I'd want this string (under my locale):

@"1,234 doodads"

Thanks.

A: 

Use an NSNumberFormatter.

Dave DeLong
So the absolute easiest way to do this is `[NSString stringWithFormat:@"%d doodads", [[[NSNumberFormatter alloc] autorelease] stringFromNumber:n]]];`? As that is more verbose than I hoped.
Max Howell
Max Howell: Normally, you would hold on to the number formatter in an instance variable (which you can make an outlet to keep the formatter in a nib), which makes the expression simply `[myFormatter stringFromNumber:[NSNumber numberWithInt:n]]`. (Also, you generally should use `NSInteger` and `numberWithInteger:`, not `int` and `numberWithInt:`, to take advantage of greater range on 64-bit machines.)
Peter Hosey
I can't get this to work. Even using setHasThousandSeparators:YES changes nothing — no thousand separators.
Max Howell
A: 

This was the only way I could make it work.

NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[formatter setFormat: @"#,###"];
NSString* doodads = [formatter stringFromNumber:[NSNumber numberWithInt:n]];
[formatter release];

The docs aren't clear if this is properly localised or not. I'm guessing no, it isn't, it will always use commas. Which sucks.

Max Howell
A: 

For 10.6 this works:

numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior: NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
NSString *numberString = [numberFormatter stringFromNumber: [NSNumber numberWithInteger: i]];

And it properly handles localization.

Todd Ransom