简体   繁体   中英

NSString To NSNumber

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);

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]);

@Aaron Wojnowski,

Use NSNumberFormatter If you want, you can set grouping separator also.

NSNumberFormatter *formatString = [[NSNumberFormatter alloc] init];
stringValue = textfield.text;
NSNumber *reqNumber = [formatString numberFromString:stringValue];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM