This question already has an answer here:
-
ios - How get the total sum of float from a NSMutableArray
3 answers
I want to sum of currency from NSMutableArray. Ex: I have an arrayA (1,234.56 , 2,345.67) and after sum items in array, I want result show: 3,580.23 to put it on the Label. Is there the way to implement this?
Thanks
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);
The simplest way is this:
NSMutableArray *array = [NSMutableArray arrayWithArray:@[@(1234.56), @(2345.67)]];
double sum = [[array valueForKeyPath: @"@sum.self"] doubleValue];