Question

what is the best way on how to deal with integers, NSStrings and NSNumberFormatter ?

I have an app with an UITextField, where users can input numbers. By every change in the UITextField, my app is immediately taking the input, put it in my function that makes a calculation, and outputs the result in an UILabel.

people can work with large numbers here, so in order to make it easier for them to read what their input is, I decided that I want to make it possible so that the input changes as soon as they insert it.

For example, when you type in 1000 that it automatically changes into 1,000. when you type in 100000000000 it automatically changes into 100,000,000,000 etc.

This I was able to do myself, like this:

formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
self.inputField.text = [formatter stringFromNumber:[formatter numberFromString:self.inputField.text]];

maybe not the best way, but it works.

my function expects an int as input, so up till 999 it's very easy: i can do the following:

[self.inputField.text integerValue];

and it works

but whenever I have 1000 or higher in my UITextField, self.inputField.text property will be 1,000 .. and then things go wrong with using the integerValue from it.

So my question is, how can I go back from NSString to an int, when there are decimals in it ?

Was it helpful?

Solution

Use the -numberFromString function to get an NSNumber from the string, then use the intValue from the NSNumber class to get the integer value:

NSString *string = @"1,000";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *number = [formatter numberFromString:string];
int intValue = [number integerValue];// intValue = 1000
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top