我的NSString值为@“78000”。我如何以货币格式获得此信息,即78,000美元仍然是NSString。
答案 0 :(得分:21)
您需要使用数字格式化程序。请注意,这也是您以正确的用户区域设置格式显示日期/时间等的方式
// alloc formatter
NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init];
// set options.
[currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
[currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *amount = [NSNumber numberWithInteger:78000];
// get formatted string
NSString* formatted = [currencyStyle stringFromNumber:amount]
[currencyStyle release];
答案 1 :(得分:3)
答案 2 :(得分:3)
上面的答案将转换一个数字,但这是一种实际将NSString转换为货币格式的方法
- (NSString*) formatCurrencyWithString: (NSString *) string
{
// alloc formatter
NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init];
// set options.
[currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
// reset style to no style for converting string to number.
[currencyStyle setNumberStyle:NSNumberFormatterNoStyle];
//create number from string
NSNumber * balance = [currencyStyle numberFromString:string];
//now set to currency format
[currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
// get formatted string
NSString* formatted = [currencyStyle stringFromNumber:balance];
//release
[currencyStyle release];
//return formatted string
return formatted;
}