문제

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];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top