Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to format a number with thousand separators to an NSString according to the Locale

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.

like image 798
mxcl Avatar asked Nov 17 '09 21:11

mxcl


2 Answers

For 10.6 this works:

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

And it properly handles localization.

like image 138
Todd Ransom Avatar answered Nov 09 '22 08:11

Todd Ransom


I have recently discovered this one-liner:

[@1234567 descriptionWithLocale:[NSLocale currentLocale]];  // 1,234,567 

Or in Swift 2:

1234567.descriptionWithLocale(NSLocale.currentLocale())     // 1,234,567 

Swift 3/4:

(1234567 as NSNumber).description(withLocale: Locale.current) 

Formatted per the question:

[@(n) descriptionWithLocale:[NSLocale currentLocale]]; 

Formatted without Objective-C literals:

[[NSNumber numberWithInt:n] descriptionWithLocale:[NSLocale currentLocale]]; 

This is the solution I was looking for when I asked the question. Available since iOS 2.0 and OS X 10.0, documented to return a string version of the number formatted as per the locale provided. stringValue is even documented to use this method but passing nil.

Seeing as it is my question and this fits my answer best, I am tempted to change the tick, but it seems cruel. Update I changed the tick, this answer is the answer.

like image 44
mxcl Avatar answered Nov 09 '22 10:11

mxcl