Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine whether a TextField contains a numeric string?

I get a value from a TextField and I need to check if there's a number in it. Whether it's a float or an integer doesn't really matter, but definitely a "Number"

How can I catch this?

This is what I'm doing so far - even if the obj is 123 (actually a number), the condition is false, so I can't get into the if. I already tried NSValue and Data, but with the same results.

id obj = self.textArea.text;

if ([obj isKindOfClass:[NSNumber class]]) {
    self.weight = [NSNumber numberWithFloat:([self.textArea.text floatValue])];
like image 492
Helen Wood Avatar asked Jun 28 '13 01:06

Helen Wood


People also ask

How do I check if a string contains numeric values?

To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.

How do I check if a string is text or number?

To check whether a text string is a number, ie whether it contains only valid number characters, you can use the following syntax with the IsNumber function: IsNumber(<text value>) <text value> is a number.

How do you check if a character in a string is numeric?

We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.

How do you check if something is a string or an integer?

The isdigit() method is an attribute of the string object to determine whether the string is a digit or not. This is the most known method to check if a string is an integer. This method doesn't take any parameter, instead, it returns True if the string is a number (integer) and False if it's not.


1 Answers

The text of a text field will ALWAYS be a NSString since that is how the class was designed.

Your task, then, is to convert it into a NSNumber. The best way to do this is to use a number formatter like this:

NSNumberFormatter *formatter = [NSNumberFormatter new];
self.weight = [formatter numberFromString:self.textArea.text];
if (!self.weight) {
    // No valid number was found.
}
like image 125
lnafziger Avatar answered Oct 18 '22 23:10

lnafziger