NSNumberFormatter货币负数

时间:2011-02-11 07:15:10

标签: iphone

我用这个

NSNumberFormatter *f = [[[NSNumberFormatter alloc]init]autorelease];
[f setNumberStyle:NSNumberFormatterCurrencyStyle];
[f setCurrencySymbol:NSLocalizedString(@"CURRENCY", @"Get Currency")];
NSString * stringCurrecy = [f stringFromNumber:(-70.00)];

我使用NSLog并检查“stringCurrecy”是“($ 70.00)” 我改变了“(”,“)”符号。如何改变这个符号。

($ 70.00) - > - $ 70.00或$ -70.00

可以

4 个答案:

答案 0 :(得分:8)

你必须设置负格式
添加以下行:

[f setNegativeFormat:@"-¤#,##0.00"];

但也许你只想用[f setLocale:]设置语言环境,而不是自己设置每个格式选项。

下次发布编译的代码。

答案 1 :(得分:5)

我有一个NSNumber类别可以做到这一点:

@implementation NSNumber (Formatter)

- (NSString *)currencyStringValue
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.locale = [NSLocale currentLocale];
    formatter.numberStyle = NSNumberFormatterCurrencyStyle;
    formatter.negativePrefix = [NSString stringWithFormat:@"- %@", formatter.currencySymbol];
    formatter.negativeSuffix = @"";

    return [formatter stringFromNumber:self];
}

@end

答案 2 :(得分:1)

将negativeFormat设置为“ - ”几乎对我有用,但它正在放弃货币符号。至少对于en_US语言环境,这符合我的需求:

NSLocale *US = [NSLocale localeWithLocaleIdentifier:@"en_US"];
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormatter setCurrencyCode:currencyCode];
[currencyFormatter setLocale:priceLocale];

//manually add - prefix to positive format...
NSString *negFormat = [NSString stringWithFormat:@"-%@",currencyFormatter.positiveFormat];
[currencyFormatter setNegativeFormat:negFormat];

我不确定这是否适合所有语言环境,但适用于en_US。

答案 3 :(得分:0)

只需将负格式设置为减号:

[f setNegativeFormat:@"-"];