Reputation: 3
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;
Upvotes: 0
Views: 421
Reputation: 318794
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.
Upvotes: 3