我知道这种问题不应该问。但是,我在没有任何线索的情况下在这里停留了几天。所以,我真的需要帮助。
我有一个核心数据对象,比如说产品。
//产品
NSDecimalNumber *数量
NSDecimalNumber *价格
我要做的是总结价格并将其设置为标签。我搜索并发现这里的一些主题说 NSDecimalNumber 不能进行标准匹配操作,因为它是一个包装实际值的对象。必须通过 完成十进制数加法 和 decimalNumberByMultiplyingBy .所以,我写了下面的代码,
NSDecimalNumber *totalPrice = [[NSDecimalNumber alloc] initWithDouble:0.0];
[self.productArray enumerateObjectsUsingBlock:^(Product *product, NSUInteger idx, BOOL *stop) {
[totalPrice decimalNumberByAdding:[product.price decimalNumberByMultiplyingBy:product.quantity]];
NSLog(@"%@", totalPrice);
NSLog(@"%@", totalPrice.doubleValue);
NSLog(@"%@", totalPrice.decimalValue);
}];
这些 NSLog 都没有显示正确的结果。他们既没有显示 0 也没有显示 NULL
但是,如果我 NSLog 以下代码,可以显示正确的结果。
[product.price decimalNumberByMultiplyingBy:product.quantity]
你能帮我指出我在这里想念什么吗?
最佳答案
您没有分配返回值。
[totalPrice decimalNumberByAdding:[product.price decimalNumberByMultiplyingBy:product.quantity]];
应该:
totalPrice = [totalPrice decimalNumberByAdding:[product.price decimalNumberByMultiplyingBy:product.quantity]];
由于 decimalNumberByAdding 返回一个值,因此不会自动更新变量。因此,totalPrice 始终为 0,这是您在初始化时分配的值。
关于iphone - 将 NSDecimalNumber 与 NSDecimalNumber 相乘返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11559835/