1

I have a string like

NSString* str = @"[\"40.00\",\"10.00\",\"60.05\"]";

I need the total string amount "110.05"

Daniel
  • 20,420
  • 10
  • 92
  • 149
SG iOS Developer
  • 158
  • 2
  • 10
  • 2
    Possible duplicate of [How get the total sum of NSNumber's from a NSArray?](http://stackoverflow.com/questions/11192503/how-get-the-total-sum-of-nsnumbers-from-a-nsarray) – Bhavin Bhadani Mar 30 '16 at 11:02
  • @EICaptain my code:- for(int i=0;i<[_orderObj.itemArray count];i++) { NSString *atemp=[_orderObj.itemArray valueForKeyPath:@"price"]; NSLog(@"title %@", atemp); } OutPut:- title ( "440.00", "510.00", "560.00" ) How get the total sum from nsstring – SG iOS Developer Mar 30 '16 at 11:11
  • @SaurabhGupta : check my answer... is that you needed? – Fahim Parkar Mar 30 '16 at 11:13

2 Answers2

1

How about this?

float myTotal = 0;
for(int i=0;i<[_orderObj.itemArray count];i++) {
    NSString *atemp=[_orderObj.itemArray valueForKeyPath:@"price"];
    NSLog(@"title %@", atemp);
    myTotal = myTotal + [atemp floatValue];
}
NSLog(@"final total==%f", myTotal);
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
1

You can proceed as follows:

1. Make an array out of the string. Since the array is in JSON format, you can do it like this:

NSString* str = @"[\"40.00\",\"10.00\",\"60.05\"]";
NSArray *stringArray = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

2. Convert the strings to double and add them up

double sum = 0;
for (NSString *value in stringArray) {
    sum += [value doubleValue];
}

3. Convert the sum back to a NSString:

NSString *sumStr =[[NSString alloc] initWithFormat:@"%f", sum];

Note that approaches that convert NSString to double or float may cause rounding errors, to overcome this issue you must use NSDecimalNumber instead.

Daniel
  • 20,420
  • 10
  • 92
  • 149