简体   繁体   English

DecimalNumberByAdding如何工作?

[英]How does DecimalNumberByAdding work?

I have a situation which I need to add two NSDecimals and this is the code that I have: 我有一种情况,我需要添加两个NSDecimals,这是我的代码:

NSDecimalNumber *total = [[NSDecimalNumber alloc] initWithString:@"0"];
for (Product* product in cartItems) {
    NSDecimalNumber *prodPrice = [[NSDecimalNumber alloc] init];
    prodPrice = product.price;
    total = [total decimalNumberByAdding:prodPrice];
}
return total;

It is completely working when I try to add two numbers such as 0.01 and 0.02 and it is giving me the 0.03. 当我尝试将两个数字相加(例如0.01和0.02)并给我0.03时,它完全可以工作。

But when I use a whole number it doesn't work. 但是,当我使用整数时,它不起作用。 As an example when I try to add 0.01 and 1, it give me a negative number as a result. 例如,当我尝试添加0.01和1时,结果为负数。 Can anyone help me with this issue? 谁能帮我解决这个问题?

Thanks 谢谢

I modified your loop slightly. 我稍微修改了您的循环。 The assignment productPrice = product.price is surely wrong in your code. 分配productPrice = product.price在代码中肯定是错误的。 Look at this: 看这个:

NSArray *cartItems = [NSArray arrayWithObjects:@"1", @".01", nil];
NSDecimalNumber *total = [[NSDecimalNumber alloc] initWithString:@"0"];

for (NSString *price in cartItems) {
    NSDecimalNumber *prodPrice = [[NSDecimalNumber alloc] initWithString:price];
    total = [total decimalNumberByAdding:prodPrice];
}
NSLog(@"Total: %@", total);

returns 退货

 2012-09-13 15:04:03.815 Searcher[69779:f803] TotalL 1.01

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

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