2016-09-21 3 views
-3
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"22,343", @"44,323",@"34,5678",@"22,725", nil]; 

Ich habe dieses Array und ich möchte zwei Werte dieses Array summieren. so array[0] + array [1]Wie summiere ich zwei Elemente des Arrays?

wie summiert man diese Elemente? danke !!

+0

Haben Sie etwas selbst ausprobiert? – Tavo

+0

ja ich habe versucht zu verdoppeln mydouble1 = array [0]; double mudouble2 = Array [1]; aber diese Methode ist falsch –

+2

'Array [ANIndex]' ist ein 'NSString' Objekt aus Ihrem Beispielcode, nicht ein' int', 'NSInteger' oder andere primitive. Also 'NSInteger sum = [array [0] ganzzahligerWert] + [array [1] ganzzahligerWert]; ' – Larme

Antwort

0

Lösung ist

NSString *strVaue1 = [array[0] stringByReplacingOccurrencesOfString:@"," withString:@""]; 
NSString *strVaue2 = [array[1] stringByReplacingOccurrencesOfString:@"," withString:@""]; 
NSUInteger arrValue1 = [strVaue1 integerValue]; 
NSUInteger arrValue2 = [strVaue2 integerValue]; 
NSUInteger sum = arrValue1 + arrValue2; 
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init]; 
[fmt setNumberStyle:NSNumberFormatterDecimalStyle]; // to get commas (or locale equivalent) 
[fmt setMaximumFractionDigits:0]; // to avoid any decimal 
NSString *result = [fmt stringFromNumber:@(sum)]; 
NSLog(@"The result is - %@",result); 

Das Druckergebnis

ist
The result is - 66,666 
Verwandte Themen