我的iPhone应用程序使用setCurrencyCode将NSDecimalNumber格式化为货币,但另一个屏幕仅显示货币符号。而不是存储货币代码和符号,是否可以从代码中派生符号?我认为以下可能有效,但它只返回符号$:
currencyCode = [dictPrices valueForKey:@"currencyCode"];
NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setCurrencyCode:currencyCode];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *currencySymbol = [numberFormatter currencySymbol];
答案 0 :(得分:6)
您可以使用货币代码从数字中获取带货币符号的数字。
这就是我的方式:
NSString *currencyCode = @"HKD";
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setCurrencyCode:currencyCode];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
cell.amountLabel.text = [numberFormatter stringFromNumber: expense.exAmount];
答案 1 :(得分:5)
您希望设置区域设置,而不是货币代码。然后,您将从格式化程序属性中获得预期结果(或调整它们)。您还可以从区域设置对象本身获取货币符号等内容。因此,例如,如果您在JPY中显示为日本格式化的数字:
NSLocale* japanese_japan = [[[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"] autorelease];
NSNumberFormatter *fmtr = [[[NSNumberFormatter alloc] init] autorelease];
[fmtr setNumberStyle:NSNumberFormatterCurrencyStyle];
[fmtr setLocale:japanese_japan];
现在,您的数字格式化程序应根据指定区域设置中的规则为您提供货币符号和格式的正确符号。
答案 2 :(得分:0)
以下代码仅返回给定currencyCode的currencySymbol
- (NSString*)getCurrencySymbolFromCurrencyCode:(NSString*)currencyCode {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setCurrencyCode:currencyCode];
[formatter setMaximumFractionDigits:0];
NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:0]];
[formatter release];
return [string substringFromIndex:1];
}
答案 3 :(得分:0)
我实际上是这样做的。如果您决定这样做,因为SveinnV说可能是符号位于0
金额之前,然后您只是将@"0"
作为符号:
- (NSString *) currencySymbolForCurrencyCode:(NSString *) currencyCode
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setMaximumFractionDigits:0];
[formatter setCurrencyCode:currencyCode];
NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:0]];
NSArray *components = [string componentsSeparatedByCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
return [components firstObject];
}
答案 4 :(得分:0)
NSNumberFormatter * formatter = [NSNumberFormatter new];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
NSString * localeIde = [NSLocale localeIdentifierFromComponents:@{NSLocaleCurrencyCode: currencyCode}];
formatter.locale = [NSLocale localeWithLocaleIdentifier:localeIde];
NSString * symbol = formatter.currencySymbol;