2

我目前的代码是

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

NSLog用来检查字符串货币,它正在打印“($ 70.00)”。我改变了“(”,“)”符号。我怎样才能做到这一点:

( $ 70.00 ) -> - $70.00 or $ -70.00
4

3 回答 3

8

您必须设置否定格式。添加这一行:

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

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

(以及下一次发布编译的代码。)

于 2011-02-11T07:53:23.967 回答
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
于 2012-09-04T18:56:41.253 回答
2

将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。

于 2014-07-23T02:10:44.850 回答