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.
This question is related to
ios
objective-c
xcode
ios4
You can also use like :
NSInteger getVal = [self.string integerValue];
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
Yet another way: if you are working with a C string, e.g. const char *, C native atoi()
is more convenient.
NSString *string = /* Assume this exists. */;
int value = [string intValue];
I use:
NSInteger stringToInt(NSString *string) {
return [string integerValue];
}
And vice versa:
NSString* intToString(NSInteger integer) {
return [NSString stringWithFormat:@"%d", integer];
}
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;
Very easy..
int (name of integer) = [(name of string, no ()) intValue];
Swift 3.0:
Int("5")
or
let stringToConvert = "5"
Int(stringToConvert)
How about
[@"7" intValue];
Additionally if you want an NSNumber
you could do
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:@"7"];
To convert an String number to an Int, you should do this:
let stringNumber = "5"
let number = Int(stringNumber)
Source: Stackoverflow.com