如何从 NSMutableArray 获取货币总和 [英] How get the total sum of currency from a NSMutableArray
问题描述
我想从 NSMutableArray 计算货币总和.例如:我有一个 arrayA (1,234.56 , 2,345.67) 并且在对数组中的项目求和之后,我希望结果显示:3,580.23 将它放在标签上.有没有办法实现这个?
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?
谢谢
推荐答案
如果值存储为 NSNumber
对象,则可以使用集合运算符.例如:
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"];
如果您想使用 NSNumberFormatter
很好地格式化 sum
:
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);
<小时>
如果您的值确实由字符串表示,@"1,234.56"
、@"2,345.67"
等,那么您可能需要手动遍历数组,使用 NSNumberFormatter
将它们转换为数值,然后将它们相加:
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);
这篇关于如何从 NSMutableArray 获取货币总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!