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
To convert an String number to an Int, you should do this:
let stringNumber = "5"
let number = Int(stringNumber)
Yet another way: if you are working with a C string, e.g. const char *, C native atoi()
is more convenient.
I use:
NSInteger stringToInt(NSString *string) {
return [string integerValue];
}
And vice versa:
NSString* intToString(NSInteger integer) {
return [NSString stringWithFormat:@"%d", integer];
}
How about
[@"7" intValue];
Additionally if you want an NSNumber
you could do
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:@"7"];
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
See the NSString Class Reference.
NSString *string = @"5";
int value = [string intValue];