0

I have this code

int countCosts = [Costs count];
countCosts = countCosts - 1;
NSDecimalNumber* Total = [[NSDecimalNumber alloc] initWithString:[NSString    stringWithFormat:@"%f", 0.0]];
NSDecimalNumber *cost = 0;
    while (countCosts != -1)
    {
        cost = [Costs objectAtIndex:countCosts];
        Total = [Total decimalNumberByAdding:cost];
        countCosts = countCosts - 1;
        if (countCosts < 0)
            break;
    }

Costs (Array has 1.10, 2.25, 3.50) in it. Total should equal the total of all items in cost. But equals 0;

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • What is `Total` before the loop starts? And does the `Costs` array contain `NSDecimalNumber`s? – Rich Apr 27 '14 at 21:17
  • Total is 0, costs array contains contents on plist. 2.60 1.10 1.10 1.10 1.10 2.85 2.85 1.10 1.10 1.10 1.10 1.10 2.85 2.85 1.10 1.10 – user3579247 Apr 29 '14 at 00:03
  • This shows the values as strings, not numbers. Where do you convert each string to an `NSDecimalNumber`? – rmaddy Apr 29 '14 at 00:13

1 Answers1

3

Your logic for adding all of the costs in the Costs array is a bit strange. Try this:

NSDecimalNumber *total = [NSDecimalNumber zero];
for (NSString *cost in Costs) {
    NSDecimalNumber *num = [NSDecimalNumber decimalNumberWithString:cost];
    total = [total decimalNumberByAdding:num];
}

NSLog(@"total = %@", total);

BTW - standard naming conventions dictates that classes begin with uppercase letters while methods and variables begin with lowercase letters.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Code works (sort of) total ends up equaling 0.00000000000000000000000000000000000000000000000000000000000000000000000000000000002019549956304625021096371054384448 not 26.10 like it should. any ideas? – user3579247 Apr 28 '14 at 23:59
  • Run the code in the debugger and look at `total` and `cost` in each iteration of the loop. Do you see anything unexpected? – rmaddy Apr 29 '14 at 00:01
  • cost is normal, but total gets smaller and smaller – user3579247 Apr 29 '14 at 00:08
  • Are you sure that each value in the `costs` array is an `NSDecimalNumber`? – rmaddy Apr 29 '14 at 00:12
  • costs array contains contents on plist. 2.60 1.10 1.10 1.10 1.10 2.85 2.85 1.10 1.10 1.10 1.10 1.10 2.85 2.85 1.10 1.10 – user3579247 Apr 29 '14 at 00:19
  • That's the problem. The values are strings, not numbers. See my updated answer. – rmaddy Apr 29 '14 at 00:23