I have a string like
NSString* str = @"[\"40.00\",\"10.00\",\"60.05\"]";
I need the total string amount "110.05"
I have a string like
NSString* str = @"[\"40.00\",\"10.00\",\"60.05\"]";
I need the total string amount "110.05"
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);
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.