Reputation: 1143
I've got this little problem. When I have a string "3 568 030" and I use [myString intValue]; it gives me result just 3, the problem is I want to convert the whole number into int/nsinteger. The string always contains just the number if that's any help. I tried using replaceoccurencesofstring (or what is the name) and it somehow didn't work...
Thanks
Upvotes: 11
Views: 29419
Reputation: 3045
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:@"42"];
[f release];
Upvotes: 1
Reputation: 1443
First, remove all the whitespaces in your original string using :
NSString *trimmedString = [yourOriginalString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Then, you can convert it to an int/NSInteger. beware: using [myString intValue]
will cast your string to an int, but [myString integerValue]
will cast it to a NSInteger.
Upvotes: 2
Reputation: 18488
That is because of the spaces on your string you will have to remove the whitespaces first like this:
NSString *trimmedString = [myString stringByReplacingOccurrencesOfString:@" " withString:@""];
NSInteger *value = [trimmedString intValue];
Upvotes: 8
Reputation: 10005
Do:
NSString *str = @"3 568 030";
int aValue = [[str stringByReplacingOccurrencesOfString:@" " withString:@""] intValue];
NSLog(@"%d", aValue);
output
3568030
Upvotes: 29
Reputation: 32066
My guess is that you're using stringByReplacingOccurencesOfString::
wrongly.
//Remove spaces.
myString = [myString stringByReplacingOccurencesOfString:@" " withString @""];
int myNumber = [myString intValue];
Upvotes: 2