Convert NSNumber to NSString with NSNumberFormatter

戏子无情 提交于 2019-12-21 04:28:39

问题


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?


回答1:


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




回答2:


 NSNumber  *firstNumber = [[NSNumber alloc] initWithInt:1000000] ;
 NSNumberFormatter *format=[[NSNumberFormatter alloc] init];
 [format setGroupingSize:3];
 [format setCurrencyGroupingSeparator:@","];
 [format setNumberStyle:NSNumberFormatterDecimalStyle];
 NSString *convertNumber = [format stringFromNumber:firstNumber];


来源:https://stackoverflow.com/questions/5079447/convert-nsnumber-to-nsstring-with-nsnumberformatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!