繁体   English   中英

将NSDecimalNumber乘以NSDecimalNumber返回0

[英]Multiply NSDecimalNumber with NSDecimalNumber return 0

我知道不应该问这种问题。 但是,我在这里呆了几天毫无头绪。 所以,我真的需要帮助。

我有一个核心数据对象,比方说产品。

//产品
NSDecimalNumber *数量
NSDecimalNumber *价格

我要尝试的是汇总价格并将其设置为标签。 我搜索并发现一些主题,它说NSDecimalNumber无法进行标准匹配操作,因为它是包装实际值的对象。 必须通过decimalNumberByAddingdecimalNumberByMultiplyingBy完成 因此,我编写了以下代码,

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,这就是您在init上分配的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM