NSString To NSNumber
Asked Answered
C

4

20

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);
Cchaddie answered 1/4, 2013 at 5:34 Comment(5)
related : #1449304Honour
I saw that before asking. But when I ran that code, I got: 159348080 Cchaddie
please post your code,where you ar getting value from textfiledClouse
here it is. None of that workedCchaddie
these all codes are not in the same method i guess. you defined both int number and NSNumber * number. it must give an error for redefinitionSoul
E
50

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
Envelop answered 1/4, 2013 at 5:54 Comment(1)
I think it was the numberWithInteger and integerValue parts that made it work for whatever reason. Anyway, Thanks a lot.Cchaddie
M
7
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.

Methadone answered 1/4, 2013 at 7:5 Comment(0)
W
3

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]);
Witkin answered 1/4, 2013 at 5:36 Comment(3)
Shouldn't the second line be, NSNumber *number = [NSNumber numberWithInt:[string intValue]];?Aplacental
This uses NSNumber literals which amount to the same thing.Witkin
Oooopssss. Use "%@" since it's an object. facepalmWitkin
K
3

@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];
Kho answered 1/4, 2013 at 5:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.