Ok so I have NsMutable array with Strings which are in format:
32,45,54,5550 etc.
What is the easiest way to convert all these strings to nsnumber and also get the sum of entire array.
Ok so I have NsMutable array with Strings which are in format:
32,45,54,5550 etc.
What is the easiest way to convert all these strings to nsnumber and also get the sum of entire array.
You can use the KVC collection operator @sum
to get the summation of all number strings stored in an array
NSArray *numberStrings = @[@"32",@"45",@"54",@"5550"];
NSNumber* sum = [numberStrings valueForKeyPath: @"@sum.self"];
NSLog(@"%@", sum);
output: 5681
For simple strings it works. But caution: in localization there might be traps. There-for I would still suggest to use a NSNumberFormatter to create real NSNumber objects, store them in another array and use @sum
on that.
Thanks Bryan Chen for make me test.
To raise the awareness for problems that might lie in localization, I want to share this experiment with you:
In German we use ,
to separate the decimal digits, where as we use the .
to group long numbers in thousands.
So if the numberString array might be filled with german formatted numbers, it might look like @[@"32,5", @"45", @"54", @"5.550,00"]
. The sum of this is 5681.5
, but if we do not alter the code, it will not fail, but worse — miscalculate: 136.55
. It just ignored everything past a comma and treated .
as decimal separator.
Lets use a NSNumberFormatter to fix it:
My system is set to german locale
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
nf.locale = [NSLocale currentLocale];
[nf setGroupingSize:3];
nf.usesGroupingSeparator= YES;
NSArray *numberStrings = @[@"32,5", @"45", @"54", @"5.550,00"];
NSMutableArray *numbers = [@[] mutableCopy];
for (NSString *s in numberStrings) {
NSNumber *n = [nf numberFromString:s];
[numbers addObject:n];
}
NSNumber* sum = [numbers valueForKeyPath: @"@sum.self"];
NSLog(@"%@", sum);
it prints correctly 5681.5
.
NSArray *array = @[ @"1,2", @"3,4" ];
NSUInteger sum = 0;
for (NSString *str in array)
{
for (NSString *num in [str componentsSeparatedByString:@","])
{
sum += [num intValue];
}
}
or
NSArray *array = @[ @"1", @"3" ];
NSUInteger sum = 0;
for (NSString *num in array)
{
sum += [num intValue];
}