how to add total number for NSString - ios

I have a string like
NSString* str = #"[\"40.00\",\"10.00\",\"60.05\"]";
I need the total string amount "110.05"

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.

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);

Related

Changing NSString value (displayed as number) to two decimal places and make a percentage

When I retrieve my JSONResponse i retrieve a number that appears as 0.2434309606330154. This is the number I want, however it isn't in the format that I want. It is set up in a way that with three other response it equals to 1.
I've tried converting it to an NSNumber but it didn't work.
NSDictionary *parameters = #{
#"data": text.text,
};
NSMutableString *parameterString = [NSMutableString string];
for (NSString *key in [parameters allKeys]) {
if ([parameterString length]) {
[parameterString appendString:#"&"];
}
[parameterString appendFormat:#"%#=%#", key, parameters[key]];
}
NSLog(#"A: %#", jsonResponse[#"results"][#"A"]);
ALabel.text = [NSString stringWithFormat:#"%#",jsonResponse[#"results"][#"A"]];
NSString *string = [NSString stringWithFormat:#"%#",jsonResponse[#"results"][#"A"]];
CGFloat float = [string floatValue];
ALabel.text = [NSString stringWithFormat:#"%.02f",float];
In Swift 1.2:
self.ALabel?.text = NSString(format: "%.02f%%", string.floatValue) as String
NSString *string = [NSString stringWithFormat:#"%#",jsonResponse[#"results"][#"A"]];
ALabel.text = [NSString stringWithFormat:#"%.02f%%",string.floatValue];
Here output will be - 0.24%

How to add array values in a string in ios

Can anybody please tell me how to put array values[Adding Values] into a string or integer.
Suppose an array a=[1,2,3].
After Adding(+ Action) it should be like
string=1+2+3=>6
Thanks and regards,
Use KVC Collection Operator
NSArray *array =#[#(1),#(2),#(3)];
NSLog(#"Sum is : %#", [array valueForKeyPath:#"#sum.self"]);
Simply loop over your string array and sum it up?!
NSArray *array = #[#"1", #"2", #"3"];
NSInteger sum = 0;
for (NSString *string in array) {
sum += [string integerValue];
}
NSLog(#"%ld", (long)sum);
NSArray *array = #[#1, #2, #3];
int sum = 0;
for (NSNumber * number in array)
{
sum += [number intValue];
}
NSString *result = [NSString stringWithFormat:#"%d", sum];
You can use KVC..
NSNumber *num1 = [NSNumber numberWithInt:1];
NSNumber *num2 = [NSNumber numberWithInt:2];
NSNumber *num3 = [NSNumber numberWithInt:3];
NSArray *arr1= #[num1, num2, num3];
NSString *str = [arr1 valueForKeyPath:#"#sum.intValue"];
NSLog(#"%#",str);
You can use:
NSArray *array = #[#1, #2, #3];
NSInteger sumArray = [[array valueForKeyPath:#"#sum.integerValue"] integerValue];
*I converted the final value to integer, if you don't need then you can replace it by:
NSString *sumArray = [array valueForKeyPath:#"#sum.integerValue"];
It's overkill to use NSArray.
Use plain C array.
int myArray[] = {1,2,3};
int i = 0; int sum= 0;
for (i=0; i < 3; i++){
sum += myArray[i];
}
char str[15];
sprintf(str, "%d", sum);
printf("%s", str);

Parse all integers from string in Objective-C

I have a problem how to get all integer values from string in Objective-C
NSString *numbers = #"1, 2";
int number = [numbers intValue];
But this just takes the first number (1) but I need both of them.
Thank you guys.
Try something like this:
NSArray *listOfNumbers = [numbers componentsSeparatedByString:#","];
for (NSString *numberAsString in listOfNumbers) {
int number = [numberAsString intValue]; // you might want to trim the string first
}
This is for if they're always separated by a ", ":
NSString *numbers = #"1, 2";
NSArray *numberTokens = [numbers componentsSeparatedByString:#", "];
for (NSString *token in numberTokens) {
NSLog(#"%i", token.integerValue);
}
This solution allows you to specify multiple characters that might separate the numbers:
NSString *numbers = #"1, 2";
NSArray *numberTokens = [numbers componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#", "]];
for (NSString *token in numberTokens) {
if (token.length > 0) {
NSLog(#"%#: %i", token, token.integerValue);
}
}

How convert string utf-8?

i've an NSString like this:
NSString *word = #"119,111,114,100"
So, what i want to do is to convert this NSString to word
So the question is, in which way can i convert a string to a word?
// I have added some values to your sample input :-)
NSString *word = #"119,111,114,100,32,240,159,145,141";
// Separate components into array:
NSArray *array = [word componentsSeparatedByString:#","];
// Create NSData containing the bytes:
NSMutableData *data = [[NSMutableData alloc] initWithLength:[array count]];
uint8_t *bytes = [data mutableBytes];
for (NSUInteger i = 0; i < [array count]; i++) {
bytes[i] = [array[i] intValue];
}
// Convert to NSString (interpreting the bytes as UTF-8):
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", str);
Output:
word 👍
Try this:
NSString *word = #"119,111,114,100";
NSArray *array=[word componentsSeparatedByString:#","];
for (NSString *string in array) {
char character=[string integerValue];
NSLog(#"%c",character);
}
Output:
w
o
r
d
libicu it's an UTF8 library that supports a conversion from an array of bytes as stated here.
The thing is, it offers Java, C or C++ APIs, not obj-c.

Converting an NSArray component into an integer or decimal number

I have a case where the data read from the CSV file in the app has to be converted into an integer, has to be plotted later. Currently it doesn't recognize when the data is saved as
int i=[[rows objectAtIndex:0] componentsSeparatedByString:#","];
This is the implemented code.
-(void)connection :(NSURLConnection *) connection didReceiveData:(NSData *)data{
[self serverConnect];
response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(response);
NSString *stripped1 = [response stringByReplacingOccurrencesOfString:#"\r" withString:#""];
NSArray *rows = [stripped1 componentsSeparatedByString:#"\n"];
NSArray *components;
for (int i=0;i<[rows count]; i++) {
if(i == 0 || [[rows objectAtIndex:i] isEqualToString:#""]){
continue;
}
components = [[rows objectAtIndex:i] componentsSeparatedByString:#","];
NSLog(#"data1:%# data2:%# data3:%#", [components objectAtIndex:0] ,[components objectAtIndex:1],[components objectAtIndex:2]);
}
data1, data2 and data3 are supposed to be integers.
Thanks a lot.
componentsSeparatedByString returns substrings, or instances of NSString.
components = [[rows objectAtIndex:i] componentsSeparatedByString:#","];
You just need to take each member of 'components' and get it's intValue, like so:
int myInt = [[components objectAtIndex:n] intValue];
NSArray and NSMutableArray can only contains objects. So get the integer value from it, use [object intValue]. If you need to add an integer to an array, create a NSNumber object from the integer and insert it. I know Rayfleck answered your question and i just want to point out the way how array works in iOS. Hope this helps.

Resources