How to do primary maths with cocoa and cocoa touch - ios

I'm quite new to xcode and am making a app where you put two numbers in to a text input and I don't know how to make xcode to do the adding sum, I tried this but it did not work
self.answer.text = self.label.text + self.label2.text
Does anybody know how to do this.

Use :
NSInteger firstNumber=[self.label.text integerValue];
NSInteger secondNumber=[self.label2.text integerValue];
NSInteger total=firstNumber + secondNumber;
NSString *string=[NSString stringWithFormat:#"%d",total];
self.answer.text = string;
If you want to take double value replace integerValue with doubleValue

Here is another interesting way:
//Some string with expression which was taken from self.label.text
NSString *s = #"2*(2.15-1)-4.1";
NSExpression *expression = [NSExpression expressionWithFormat:s];
float result = [[expression expressionValueWithObject:nil context:nil] floatValue];
NSLog(#"%f", result);
self.answer.text=[NSString stringWithFormat:#"%f",result];

Related

Find substring range of NSString with unicode characters

If I have a string like this.
NSString *string = #"😀1😀3😀5😀7😀"
To get a substring like #"3😀5" you have to account for the fact the smiley face character take two bytes.
NSString *substring = [string substringWithRange:NSMakeRange(5, 4)];
Is there a way to get the same substring by using the actual character index so NSMakeRange(3, 3) in this case?
Thanks to #Joe's link I was able to create a solution that works.
This still seems like a lot of work for just trying to create a substring at unicode character ranges for an NSString. Please post if you have a simpler solution.
#implementation NSString (UTF)
- (NSString *)substringWithRangeOfComposedCharacterSequences:(NSRange)range
{
NSUInteger codeUnit = 0;
NSRange result;
NSUInteger start = range.location;
NSUInteger i = 0;
while(i <= start)
{
result = [self rangeOfComposedCharacterSequenceAtIndex:codeUnit];
codeUnit += result.length;
i++;
}
NSRange substringRange;
substringRange.location = result.location;
NSUInteger end = range.location + range.length;
while(i <= end)
{
result = [self rangeOfComposedCharacterSequenceAtIndex:codeUnit];
codeUnit += result.length;
i++;
}
substringRange.length = result.location - substringRange.location;
return [self substringWithRange:substringRange];
}
#end
Example:
NSString *string = #"😀1😀3😀5😀7😀";
NSString *result = [string substringWithRangeOfComposedCharacterSequences:NSMakeRange(3, 3)];
NSLog(#"%#", result); // 3😀5
Make a swift extension of NSString and use new swift String struct. Has a beautifull String.Index that uses glyphs for counting characters and range selecting. Very usefull is cases like yours with emojis envolved

can I convert + as an NSString to addition operator directly?

I have a mathematical equation in string format.
Is there a way to convert #"+"(String constant) directly to addition operator in objective C
Or
I have to use If-Else statements to solve this equation ??
NSPredicate * parsed = [NSPredicate predicateWithFormat:#"123+456+678-985 = 0"];
NSExpression * left = [(NSComparisonPredicate *)parsed leftExpression];
NSNumber * result = [left expressionValueWithObject:nil context:nil];
float i = [result floatValue];
if([yourString isEqualToString:#"+"])
{
//Do something
}
This code should work.
You can use NSExpression to achieve this
NSString *expressionFormat = [NSString stringWithFormat:#"(%d %# %d)",firstNumber,arcthimaticOperator,secondNumber];
NSExpression *expression = [NSExpression expressionWithFormat:expressionFormat];
NSNumber *result = [expression expressionValueWithObject:nil context:nil];
NSLog(#"%#", result);
Please make sure you enter the correct format else the above code will throw exception.

ios get rid of decimal place if number is an int

I have an app that imports a long list of data of a csv.
I need to work with the numbers fetched, but in order to do this, I need to get rid of the decimal place on numbers that are ints, and leave untoched numbers that have x.5 as decimal
for example
1.0 make it 1
1.50 make it 1.5
what would be the best way to accomplish this?
thanks a lot!
You can use modf to check if the fraction part equates to zero or not.
-(BOOL)isWholeNumber:(double)number
{
double integral;
double fractional = modf(number, &integral);
return fractional == 0.00 ? YES : NO;
}
Will work for some boundary cases as well.
float a = 15.001;
float b = 16.0;
float c = -17.999999;
NSLog(#"a %#", [self isWholeNumber:a] ? #"YES" : #"NO");
NSLog(#"b %#", [self isWholeNumber:b] ? #"YES" : #"NO");
NSLog(#"c %#", [self isWholeNumber:c] ? #"YES" : #"NO");
Output
a NO
b YES
c NO
Other solutions do not work if the number is very close to a whole number. I am not sure if you have this requirement.
After that you can display them as you like using the NSNumberFormatter, one for whole numbers and one for fractions.
A simple NSNumberFormatter should achieve this for you:
float someFloat = 1.5;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setAllowsFloats:YES];
[formatter setMaximumFractionDigits:1];
NSString *string = [formatter stringFromNumber:[NSNumber numberWithFloat:someFloat]];
Of course this assumes that you only have decimals in the tenths that you want to keep, for example if you used "1.52" this would return "1.5" but judging by your last post on rounding numbers to ".5" this shouldn't be a problem.
This code achieves what you want
float value1 = 1.0f;
float value2 = 1.5f;
NSString* formattedValue1 = (int)value1 == (float)value1 ? [NSString stringWithFormat:#"%d", (int)value1] : [NSString stringWithFormat:#"%1.1f", value1];
NSString* formattedValue2 = (int)value2 == (float)value2 ? [NSString stringWithFormat:#"%d", (int)value2] : [NSString stringWithFormat:#"%1.1f", value2];
This kind of thing could be done in a category so how about
// untested
#imterface NSString (myFormats)
+(NSString)formattedFloatForValue:(float)floatValue;
#end
#implementation NSString (myFormats)
+(NSString)formattedFloatForValue:(float)floatValue
{
return (int)floatValue == (float)floatValue ? [NSString stringWithFormat:#"%d", (int)floatValue] : [NSString stringWithFormat:#"%1.1f", floatValue];
}
#end
// usage
NSLog(#"%#", [NSString formattedFloatForValue:1.0f]);
NSLog(#"%#", [NSString formattedFloatForValue:1.5f]);

Is it possible to do negative loc in the NSMakeRange?

Is it possible to do negative loc in the NSMakeRange?
NSString *string = #"abc";
NSString *myString = [string substringWithRange:NSMakeRange(-1, 1)];
No.
location and length are unsigned integers :
typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
} NSRange;
and also, NSMakeRange function is defined as follow :
NSRange NSMakeRange (
NSUInteger loc,
NSUInteger len
);
Yes, it possible, but in fact it will no sense since negative value will translated to another very big positive value.
NSUInteger loc = -1; // equal to 4294967295
1.So, you are in need of a very long string.
2.So, you need to invert your negative value to enormous big value in order to make your example worked
NSString *string = #"abc";
NSRange r1 = NSMakeRange(-NSUIntegerMax, 1);
NSString *myString = [string substringWithRange:r1];
NSLog(#"%#",myString);

Convert a string into an int

I'm having trouble converting a string into an integer. I googled it but all I can find is how to convert an int into a string. Does anyone know how to do it the other way around? Thanks.
See the NSString Class Reference.
NSString *string = #"5";
int value = [string intValue];
How about
[#"7" intValue];
Additionally if you want an NSNumber you could do
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:#"7"];
I use:
NSInteger stringToInt(NSString *string) {
return [string integerValue];
}
And vice versa:
NSString* intToString(NSInteger integer) {
return [NSString stringWithFormat:#"%d", integer];
}
This is the simple solution for converting string to int
NSString *strNum = #"10";
int num = [strNum intValue];
but when you are getting value from the textfield then,
int num = [txtField.text intValue];
where txtField is an outlet of UITextField
Swift 3.0:
Int("5")
or
let stringToConvert = "5"
Int(stringToConvert)
I had to do something like this but wanted to use a getter/setter for mine. In particular I wanted to return a long from a textfield. The other answers all worked well also, I just ended up adapting mine a little as my school project evolved.
long ms = [self.textfield.text longLongValue];
return ms;
NSString *string = /* Assume this exists. */;
int value = [string intValue];
Very easy..
int (name of integer) = [(name of string, no ()) intValue];
Yet another way: if you are working with a C string, e.g. const char *, C native atoi() is more convenient.
You can also use like :
NSInteger getVal = [self.string integerValue];
To convert an String number to an Int, you should do this:
let stringNumber = "5"
let number = Int(stringNumber)

Resources