Convert NSNumber to NSString with NSNumberFormatter

mozzer picture mozzer · Feb 22, 2011 · Viewed 12.8k times · Source

I am converting an NSNumber to an NSString assuming in this example that the selected key in "theindex" is 1000000

NSNumber  *firstNumber = [tempDict objectForKey:@"theindex"];
NSString *convertNumber = [firstNumber stringValue];

Returning the NSString "1000000"

I would like the string's value to be "1,000,000".

I am not concerned with localization, but understand from other questions that NSNumberFormatter should be implemented. I am not sure how to accomplish this?

Answer

Kris Babic picture Kris Babic · Feb 22, 2011

Here is an example using a standard formatting style of NSNumberFormatter:

NSNumber *firstNumber = [NSNumber numberWithInt:123456789];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *convertNumber = [formatter stringForObjectValue:firstNumber];
NSLog(@"value : %@", convertNumber);

Other examples you can reference at:
http://iosdevelopertips.com/cocoa/formatting-numbers-nsnumberformatter-examples.html