开发者

NSDecimal multiplication

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开发者_StackOverflow中文版 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!


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]);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜