Domanda

I have several text fields where a user enters a number and I do various calculations with that number. Since these numbers can be quite large, I have a feeling that some users might put grouping separators (commas, spaces, decimals) in their entered value.

Is there a good way to check if the user has put a grouping separator in the textfield and then delete that grouping separator so I can store the entered value as an NSNumber?

From what I can tell, NSNumberFormatter does not provide a method for this and all of my solutions seem really inefficient. I was wondering if you guys had any good ways to deal with this.

È stato utile?

Soluzione

NSNumberFormatter does provide ways to deal with commas, dots and spaces, in fact, it does this very well. There's the "leniency" that tries to guess the best formatting:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setLenient:YES];

NSLog(@"%@", [formatter numberFromString:@"123,456.78"]);
NSLog(@"%@", [formatter numberFromString:@"123 456 78"]);

Output:

123456.78
12345678

It works, but if the user starts mixing things (e.g 123,456 789.105) it fails. I would personally replace all occurrences of spaces, and then use the number formatter.

If you're worried about efficiency, I need to inform you: don't. It's just a text input that will be used once for every run. If you were doing this every time the user scrolls something, or thousands of calculations, then you should worry.

Also, if the user is going to input very large numbers, don't you think there are better interfaces for handling that? I'm not sure if you're writing an iOS or OSX app, so it depends. Maybe give him a scientific notation set of buttons, where he can pick the number and the power?

Altri suggerimenti

You can either strip away the separators using[myField.text stringByReplacingOccurrencesOfString:@" " withString:@""] ... etc (or using regular expressions).

Or you can prevent non numeric entry on the fields by specifying a number keypad as the input.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top