MaryamAyd
MaryamAyd

Reputation: 151

How does DecimalNumberByAdding work?

I have a situation which I need to add two NSDecimals and this is the code that I have:

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.

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. Can anyone help me with this issue?

Thanks

Upvotes: 0

Views: 1348

Answers (1)

David Hoerl
David Hoerl

Reputation: 41642

I modified your loop slightly. The assignment productPrice = product.price is surely wrong in your code. 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

Upvotes: 1

Related Questions