views:

147

answers:

1

Hi all,

I have a core data-based app that stores several properties in the decimal and float data types. I'm writing some transient properties / virtual accessors that run calculations and return some derived numbers, but I can't seem to get NSDecimalNumber multiplication to work.

Why does this not work:

- (NSDecimalNumber *)discountedPrice {
return ([self.orderCost decimalNumberByMultiplyingBy:self.discountPercentage]);
}
// Error: Incompatible Objective-C types 'struct NSNumber *', expected 'struct NSDecimalNumber *' when passing argument 1 of 'decimalNumberByMultiplyingBy:' from distinct ...

When this does:

- (NSDecimalNumber *)orderCost {
    return ([self.orderCost decimalNumberByAdding:self.taxes]);
}

I assume that my object gets an NSNumber from core data regardless of the storage type specified in the data model, so why does this puke and how can I make it work? Am I completely misunderstanding this here?

Thanks a bunch!

+2  A: 

You're running into problems because -decimalNumberByMultiplyingBy: expects an NSDecimalNumber, but (I presume) you're passing it an NSNumber containing a float or double value (your discount percentage). Try building an NSDecimalNumber first:

- (NSDecimalNumber *)discountedPrice {
    NSDecimalNumber *dec = [NSDecimalNumber decimalNumberWithDecimal:
                              [self.discountPercentage decimalValue]];
    return ([self.orderCost decimalNumberByMultiplyingBy:dec]);
}
Tim