How get the total sum of currency from a NSMutableArray [duplicate]

旧巷老猫 提交于 2019-12-13 11:01:21

问题


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


回答1:


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:


The simplest way is this:

NSMutableArray *array = [NSMutableArray arrayWithArray:@[@(1234.56), @(2345.67)]];
double sum = [[array valueForKeyPath: @"@sum.self"] doubleValue];


来源:https://stackoverflow.com/questions/23325660/how-get-the-total-sum-of-currency-from-a-nsmutablearray

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!