Search code examples
iosobjective-cnsarray

Calculate the average value in an array


I need to add something to my app that calculates the average of an array of numbers.

If I have 3 numbers: 10, 20, and 30, how do I take all the numbers in the array, add them together (60) and then divide by the total number and present the final number somewhere like a label?


Solution

  • In addition to katzenhut's suggestion of manually calculating the average, you can use KVC collection operators, too, e.g.:

    NSArray *array = @[@10, @25, @30];
    
    NSNumber *average = [array valueForKeyPath:@"@avg.self"];
    

    Or, if dealing with objects, for example a "Product" model object with this interface:

    @interface Product : NSObject
    
    @property (nonatomic, copy) NSString *name;
    @property (nonatomic) double price;
    
    - (id)initWithName:(NSString *)name price:(double)price; // the corresponding implementation should be obvious, so I'll not include it in this code snippet
    
    @end
    

    You could then do:

    NSMutableArray *products = [NSMutableArray array];
    [products addObject:[[Product alloc] initWithName:@"item A" price:1010.0]];
    [products addObject:[[Product alloc] initWithName:@"item B" price:1025.0]];
    [products addObject:[[Product alloc] initWithName:@"item C" price:1030.0]];
    
    NSNumber *average = [products valueForKeyPath:@"@avg.price"];
    

    If you want to take the results and populate a label with the results, you might do something like:

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    formatter.maximumFractionDigits = 2;                   // two decimal places?
    
    self.averageLabel.text = [formatter stringFromNumber:average];
    

    The advantage of NSNumberFormatter over stringWithFormat is that you have greater control over the string representation of the number, e.g. it can observe localization, employ thousandths separators, etc.