views:

758

answers:

1

Well, it's actually the sum of an array of NSDecimalNumbers I'd like to get the absolute value of... I constantly feel like I'm fighting the framework with all the conversions & typecasting that are required...from double to NSNumber to NSDecimalNumber and back and...all while trying to maintain the precision that NSDecimalNumber affords. The following works but is there an easier way that avoids all this conversion & type casting?

NSNumber *totalAmt = [customObjectArray valueForKeyPath:@"@sum.decimalNumberValue"];
NSString *totalAmtString = [currencyFormatter stringFromNumber:[NSNumber numberWithDouble:fabs([totalAmt doubleValue])]];
sectionLabel.text = [NSString stringWithFormat:@"Total: %@", totalAmtString];

perhaps I could alter the NSNumberFormatter (currencyFormatter) to ignore the - sign?

A: 

you don't need the type cast.

NSNumber *totalAmt = [customObjectArray valueForKeyPath:@"@sum.decimalNumberValue"];
NSString *totalAmtString = [currencyFormatter stringFromNumber:totalAmt];
sectionLabel.text = [NSString stringWithFormat:@"Total: %@", totalAmtString];

this will work fine because NSDecimalNumber is a subclass of NSNumber.

And if sectionLabel is something you bind in IB, try to bind the value totalAmt to 'pattern value' instead of sectionLabel to 'value'. This will save the last line :) And if customObjectArray is something you have access via an NSArrayController, then you should enter the given key path in the first line as key path in the 'pattern value' binding. Using this way you can delete all the given three lines :)

cocoafan