开发者

NSDecimal multiplication

开发者 https://www.devze.com 2022-12-23 06:09 出处:网络
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

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

精彩评论

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

关注公众号