Question

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
Was it helpful?

Solution

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.)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top