簡體   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