开发者

NSNumberFormatter currency negative number

My current code is

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

I'm using NSLog to check the string currency and it's printing "($ 70.00)". I changed "(", ")" symbol. How can 开发者_开发问答I achieve this:

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


You have to set the negative format. Add this line:

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

but maybe you just want to set the locale with [f setLocale:] instead of setting every format option on your own.

(and next time post code that does compile.)


I have a NSNumber category that does this:

@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


Setting negativeFormat to "-" almost worked for me, but it was dropping off the currency symbol. At least for en_US locale, this fits my needs:

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];

I'm not sure whether this is appropriate for all locales, but it works for en_US.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜