If the values are stored as NSNumber
objects, you can use the collection operators. For example:
NSArray *array = @[@1234.56, @2345.67];
NSNumber *sum = [array valueForKeyPath:@"@sum.self"];
If you want to format that sum
nicely using NSNumberFormatter
:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *result = [formatter stringFromNumber:sum];
NSLog(@"result = %@", result);
If your values are really represented by strings, @"1,234.56"
, @"2,345.67"
, etc., then you might want to manually iterate through the array, converting them to numeric values using the NSNumberFormatter
, adding them up as you go along:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSArray *array = @[@"1,234.56", @"2,345.67"];
double sum = 0.0;
for (NSString *string in array) {
sum += [[formatter numberFromString:string] doubleValue];
}
NSString *result = [formatter stringFromNumber:@(sum)];
NSLog(@"result = %@", result);
2
solved How get the total sum of currency from a NSMutableArray [duplicate]