So this problem has been perplexing me for way too long. I have a UIAlertView
with a textField
in it, and I need the value of the textField
as an NSNumber
. But everything I try gives me random strings of numbers. Any help would be very much appreciated.
int i = [[alertView textFieldAtIndex:0].text intValue];
NSNumber *number = [NSNumber numberWithInt:[[alertView textFieldAtIndex:0].text integerValue]];
int number = [[dict objectForKey:@"integer"] intValue];
NSLog(@"text = %@", [alertView textFieldAtIndex:0].text);
NSString *alertText = [alertView textFieldAtIndex:0].text;
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterNoStyle];
NSNumber * myNumber = [f numberFromString:[alertView textFieldAtIndex:0].text];
NSNumber *number = @([alertText intValue]);
NSString *string = @"54";
NSNumber *number = @([string intValue]);
NSLog(@"here we are: %i", number);
Use an NSNumberFormatter : NSNumberFormatter *f = [[NSNumberFormatter alloc] init]; f. numberStyle = NSNumberFormatterDecimalStyle; NSNumber *myNumber = [f numberFromString:@"42"]; If the string is not a valid number, then myNumber will be nil .
NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .
A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.
To convert a string to a double, we can use the built-in Double() initializer syntax in Swift. The Double() initializer takes the string as an input and returns the double instance.
Once see this one,
NSString *string = @"123";
NSNumber *aNum = [NSNumber numberWithInteger: [string integerValue]];
NSLog(@"%@",aNum);//NSString to NSNumber
NSInteger number=[string intValue];
NSLog(@"%i",number);//NSString to NSInteger
NSString *string = @"54";
NSNumber *number = @([string intValue]);
NSLog(@"here we are: %i", number);
Instead try using the following:
NSLog(@"here we are: %@", number);
Since you are converting to NSNumber (Object). You should use object specifier %@ in your NSLog statement.
Here's a sample with an integer and using NSNumber literals. You could also use the floatValue
method if your string contains a float.
NSString *string = @"54";
NSNumber *number = @([string intValue]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With