简体   繁体   中英

Adding multiple NSDecimalNumbers

What's the best practice for doing this:

I have an array of NSDecimalNumbers and I need to add them all together.

I was going to set up a base number and then loop and add each subsequent number to the base...sort of like this:

 NSDecimalNumber* baseNumber = [[NSDecimalNumber alloc] initWithString:[NSString stringWithFormat:@"%f", 0.0]];

    for(int i=0; i<itemsToAdd.count; i++) {
        NSDecimalNumber* thisNumber = [itemsToAdd objectAtIndex:i];
        [baseNumber decimalNumberByAdding:thisNumber];
    }

NSLog(@"%@", baseNumber);

but I keep getting 0 for the total. I thought baseNumber would increment. Obviously not. : D Here's one of the batch of numbers I am working with, they total out to 81649.64.

2013-02-05 08:58:50.833 EUS Calculator[37430:c07] 4905.6
2013-02-05 08:58:50.834 EUS Calculator[37430:c07] 13850.88
2013-02-05 08:58:50.834 EUS Calculator[37430:c07] 43246.08
2013-02-05 08:58:50.835 EUS Calculator[37430:c07] 19944.96
2013-02-05 08:58:50.835 EUS Calculator[37430:c07] 412.8
2013-02-05 08:58:50.835 EUS Calculator[37430:c07] 289.92
2013-02-05 08:58:50.836 EUS Calculator[37430:c07] 0

How can I add a batch of NSDecimalNumbers? I will eventually convert these to currency strings.

NSDecimalNumber is an immutable class. That is, once constructed, an instance doesn't change. The message decimalNumberByAdding: returns a new number. As such, you'll need to record the new instance each time around. The following code should work.

NSDecimalNumber* baseNumber = [NSDecimalNumber zero];

for (int i = 0; i < itemsToAdd.count; i++)
{
    baseNumber = [baseNumber decimalNumberByAdding:[itemsToAdd objectAtIndex:i]];
}

NSLog(@"%@", baseNumber);

Remember to retain the baseNumber if you're not using ARC and want it to hang around beyond the next autorelease pool drain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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