Convert Math equation into string - ios

![HERE is what my log is showing][1]I am working on a calculator and I have a function that takes in user input and then will display the answer just lie a normal calculator. I want to save any user input into a string such as "2+2=4" into an array which can then be viewed later.
Is there any way to convert the double values into strings? and also how would i save this string in the array.
Below is some code which i have tried, but have had no luck.
The below method is used to call the users input
NSString *leftString = [NSString stringWithFormat:#"%d + %d", left, right];
_array = [[NSArray alloc] initWithObjects: leftString, nil];

This:
NSString *leftString = [NSString stringWithFormat:#"%d", left "+" right];
should be like this:
NSString *leftString = [NSString stringWithFormat:#"%f + %f", left, right];
where the plus sign is within the expression and the %f indicates left and right are doubles.

Assuming you want to have an array like so: [left, operation symbol, right] then you do the following:
NSString *leftString = [NSString stringWithFormat:#"%f", left];
NSString *rightString = [NSString stringWithFormat:#"%f", right];
NSString *operationString= [NSString stringWithFormat:#"%#", operation];
Then do the following to add all of them into an array:
_array = [[NSArray alloc] initWithObjects: leftString, operation, rightString, nil];

Related

Listing floats from array with format

I have an NSMutableArray that contains floats. I can display one float in a specific format or display all of them without formatting but I cannot figure out how to do both at once. I first wrap the float in an NSNumber so that it can be added to the array:
NSMutableArray *array = [[NSMutableArray alloc] init];
NSNumber *num = [NSNumber numberWithFloat:5.10f];
[array addObject:num];
NSNumberFormatter works for formatting the numbers to be displayed in a textView. Here is the code I used to do that:
for (NSNumber *aNumber in array) {
self.textView.text = [NSString stringWithFormat:#"%#"
[NSNumberFormatter localizedStringFromNumber:aNumber
numberStyle:NSNumberFormatterCurrencyStyle]];
}
The obvious problem here is the text is replaced with the number in the array each time the loop runs rather than listing all of them.
So, I did more research and found componentsJoinedByString:
self.textView.text = [NSString stringWithFormat:#"%#", [array componentsJoinedByString:#", "]];
This worked well to list them but lacked the formatting style: It displays, for example, 5.10 as 5.1 which I don't want. I tried to combine them somehow but it didn't work, and I also tried stringByAppendingString in the loop using the formatter but that was a mess that did not work at all.
You are replacing the text in the textView instead of appending..
for (NSNumber *aNumber in array) {
NSString *result = [NSNumberFormatter localizedStringFromNumber:aNumber
numberStyle:NSNumberFormatterCurrencyStyle];
if (aNumber == array.firstObject && !self.textView.text.length) {
self.textView.text = result;
}
else {
self.textView.text = [NSString stringWithFormat:#"%#, %#", self.textView.text, result];
}
}

Objective C, Trim a float

I have float like 3500,435232123. All I want to know if exists (in Objective C) a function that let me keep just the last 4 digits in my case is 2123.
You can use NSNumberFormatter
NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setRoundingMode:NSNumberFormatterRoundHalfUp];
[format setMaximumFractionDigits:4];
[format setMinimumFractionDigits:4];
string = [NSString stringWithFormat:#"%#",[format stringFromNumber:[NSNumber numberWithFloat:65.50055]] ;
Or simply
NSString *string = [NSString stringWithFormat:#"%.04f", floatValue];
If you want only last four digits, convert the float to a string
NSString *string = [NSString stringWithFormat:#"%f", floatValue];
and get the last four characters
NSString *lastFour = [string substringFromIndex: [string length] - 4];
It you want to get the decimal part, you can do x - floor(x). For instance:
float x = 3500,435232123;
NSString *string = [NSString stringWithFormat:#"%.04f", x - floor(x)];
And to get 4 decimal digits do what Fawad Masud says.
No there is no such function, as far as i know. But here is a way to achieve exactly what you want.
First you have to round it to four digits after point:
NSString *exampleString = [NSString stringWithFormat:#"%.04f", valueToRound];
Then you get the location for the comma inside the exampleString:
NSRange commaRange = [valueString rangeOfString:#","];
Finally you create the finalString with the values from that NSRange. The substring starts at commaRange.location+commaRange.lengthbecause thats the index directly after the comma.
NSString *finalString = [valueString substringWithRange:NSMakeRange(commaRange.location+commaRange.length,valueString.length-commaRange.location-commaRange.length)];
Hope that helps you.
I think is no predefined function for that.
and the solution i thought of is:
float floatNum = 3500.435232123;
converting float number to string and trim/substring the string, like for example:
NSString *stringFloat = [NSString stringWithFormat:#"%f", floatNum];
NSString *newString = [stringFloat substringWithRange:NSMakeRange(stringFloat.length - 4, stringFloat.length)];
NSLog(#"%#", newString);
another is something like:
NSString *stringFloat = [NSString stringWithFormat:#"%f", floatNum];
//separates the floating number to
arr[0] = whole number
arr[1] = decimals
NSArray *arr=[str componentsSeparatedByString:#"."];
since you just want to work on the decimal, i think arr[1] is what you need..
NSString *stringDecimals = (NSString *)arr[1];
if ( stringDecimals.length > 4) //check the length of the decimals then cut if exceeds 4 character..
{
stringDecimals = [stringDecimals substringWithRange:NSMakeRange(stringDecimals.length - 4, stringDecimals.length)];
}
NSLog(#"stringDecimals: %#", stringDecimals);

present NSString as a line of elements

I have an NSString that hold data (actually that could be presented an NSArray). and i want to output that on a label.
In NSLog my NSString output is:
(
"cristian_camino",
"daddu_02",
"_ukendt_babe_",
"imurtaza.zoeb"
)
What i want is, to present it like :"cristian_camino","daddu_02","_ukendt_babe_","imurtaza.zoeb"
In a single line.
I could accomplish that turning string to an array and do following: arrayObjectAtIndex.0, arrayObjectAtIndex.1, arrayObjectAtIndex.2, arrayObjectAtIndex.3.
But thats look not good, and that objects may be nil, so i prefer NSString to hold data.
So, how could i write it in a single lane?
UPDATE:
There is the method i want to use to set text for UILabel:
-(void)setLikeLabelText:(UILabel*)label{
//Likes
NSString* likersCount = [self.photosDictionary valueForKeyPath:#"likes.count"];
NSString* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent "likes": %#", likersCount, likersRecent];
label.text = textString;
NSLog(#"text String is %#", textString);
}
valueForKeyPath: returns an NSArray, not an NSString. Whilst you've declared likersCount and likersRecent as instances of NSString, they're actually both arrays of values. You should be able to do something like the following to construct a string:
NSArray* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *joined = [likersRecent componentsJoinedByString:#"\", \""];
NSString *result = [NSString stringWithFormat:#"\"%#\"", joined];
NSLog(#"Result: %#", result);
componentsJoinedByString: will join the elements of the array with ", ", and then the stringWithFormat call will add a " at the beginning and end.
The statement is incorrect, the internal quote marks (" that you want to display) need to be escaped:
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent \"likes\": %#", likersCount, likersRecent];
If somebody curious how i fix it, there it is:
for (int i =0; i < [likersRecent count]; i++){
stringOfLikers = [stringOfLikers stringByAppendingString:[NSString stringWithFormat:#" %#", [likersRecent objectAtIndex:i]]];
}
Not using commas or dots though.

Removing last characters of NSString until it hits a separator

I've got a string that shows the stock amount using "-" as separators.
It's built up like this: localStock-wareHouseStock-supplierStock
Now I want to update the supplierStock at the end of the string, but as you can see in the code below it goes wrong when the original string returns more than a single-space value (such as 20).
Is there a way to remove all characters until the last "-" (or remove characters after the second "-")?
NSMutableString *string1 = [NSMutableString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *newString = [string1 substringToIndex:[string1 length]-2];
NSLog(#"newString: %#",newString);
NSString *colorStock = [NSString stringWithFormat:#"%#-%#",newString,p2.supplierStock];
NSLog(#"colorstock: %#",colorStock);
p1.colorStock = colorStock;
NSLog1
string1: 0-0-0
newString: 0-0
colorstock: 0-0-20
NSLog2
string1: 0-0-20
newString: 0-0-
colorstock: 0-0--20
EDIT: Got it working thanks to Srikar!
NSString *string1 = [NSString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *finalString = [string1 stringByReplacingOccurrencesOfString:[[string1 componentsSeparatedByString:#"-"] lastObject] withString:p2.supplierStock.stringValue];
NSLog(#"finalString: %#",finalString);
p1.colorStock = finalString;
Why not use componentsSeparatedByString followed by lastObject ?
NSString *supplierStock = [[string1 componentsSeparatedByString:#"-"] lastObject];
The above works if the "stock amount" is always in sets of 3's separated by a "-". Also since you always want supplierStock, lastObject is perfect for your needs.
Of course after splitting string1 with - you get a NSArray instance and you can access the individual components using objectAtIndex:index. So if you want localStock you can get by
NSString *localStock = [[string1 componentsSeparatedByString:#"-"] objectAtIndex:0];
I would suggest splitting the string into the 3 parts using [NSString componentsSeparatedByString:#"-"] and then building it back up again:
NSArray *components = [p1.colorStock componentsSeparatedByString:#"-"];
p1.colorStock = [NSString stringWithFormat:#"%#-%#-%#",
[components objectAtIndex:0],
[components objectAtIndex:1],
p2.supplierStock];
With a string that looks like
NSString *myString = #"Hello-World";
you can separate it with the componentsSeparatedByString: method of the NSString object as
NSArray *myWords = [myString componentsSeparatedByString:#"-"];
The myWords - array will then contain the two NSString objects Hello and World.
To access the strings:
NSString *theHelloString = [myWords objectAtIndex:0];
NSString *theWorldString = [myWords objectAtIndex:1];
Hope it helps!
None of these examples show how to do this if you are unaware of how many of these separator occurrences you're going to have in the original string.
Here's what I believe the correct the correct code should be for dismantling the original string and rebuilding it until you reach the final separator, regardless of how many separators it contains.
NSString *seperator = #" ";
NSString *everythingBeforeLastSeperator;
NSArray *stringComponents = [originalString componentsSeparatedByString:seperator];
if (stringComponents.count!=0) {
everythingBeforeLastSeperator = [stringComponents objectAtIndex:0];
for (int a = 1 ; a < (stringComponents.count - 1) ; a++) {
everythingBeforeLastSeperator = [NSString stringWithFormat:#"%#%#%#", everythingBeforeLastSeperator, seperator, [stringComponents objectAtIndex:a]];
}
}
return everythingBeforeLastSeperator;

IOS Array Testing

Here is my current code:
int i = 1;
NSString * StockOneYahooFinance = [NSString stringWithFormat:#"http://finance.yahoo.com/q/hp?s=S+Historical+Prices"];
NSString * PulledStockOne = [NSString stringWithContentsOfURL:[NSURL URLWithString:StockOneYahooFinance] encoding:1 error:nil];
for (i=1;i=30;i++){
NSString *StartPulling = [[PulledStockOne componentsSeparatedByString:#"nowrap align="] objectAtIndex:i];
NSString *StartOpen = [[StartPulling componentsSeparatedByString:#">"] objectAtIndex:3];
NSString *Open = [[StartOpen componentsSeparatedByString:#"<"] objectAtIndex:0];
NSString *StartClose = [[StartPulling componentsSeparatedByString:#">"] objectAtIndex:9];
NSString *Close = [[StartClose componentsSeparatedByString:#"<"] objectAtIndex:0];
year.text = Close;
i++;
}
But to the point I click the only button on the screen and it does exactly what I want it pulls the stocks open and close price for the day. But my current issue is I want it to pull all of these as an array so how can I do this?
First thing:
for (i=1;i=30;i++){
it should be:
for (i=1;i<=30;i++){
Second one, do not increment 'int i' value on the end of loop because 'for' loop already do this. For quick'n dirty way of debugging add:
NSLog(#"Current iteration: %i", i);
as the first function in 'for' loop to see what's happening there.

Resources