views:

1334

answers:

3

Hello all,

I am fairly new to iPhone development and I have what seems to be a simple question that I cannont figure out. How can I verify that a user input a number and a decimal into the text field?

I have tried many different things but the closes I can get only allows for numeric strings of the form: 5.34 or 23.89. I need it to allow numbers such as; 0.50 or 432.30, just something with a zero as the last input value. I attempted to check the string input by converting it to a float and then back to a string, but get the abovementioned results.

ANY help would be great (same with sample code!) THANKS!

A: 

why not just check that the input is only numeric and the decimal point (or comma, depending on your locale)?

Oren Mazor
That is exactly what I need to figure out. I don't know how to do this, or else I would not have posted the question.
oh sorry. my mistake.do this:TextBox foo = new TextBox();foo.Text = "asdf";Match m = Match(foo.Text,"\\W+");if(m.Success) MessageBox.Show("invalid input");
Oren Mazor
Yeah, that's not Objective-C.
Jonathan Sterling
+1  A: 

The question that Dave DeLong was trying to post is 1320295 and looks very relevant. This appears to be an old question, youve probably found your solution, Would be nice if you share it will all =)

Yarek T
A: 

You can cast the content of your textfield in float and format it by using the code below :

float myFloat = [myTextField floatValue];
NSString *formatString = [NSString stringWithFormat:@"%%1.%if", 2]; //2 decimals after point
NSString *resultString = [NSString stringWithFormat:formatString, myFloat];

If you want to allow only numeric values in your textfield, you can just reput the resultString in your textField so any not allowed text will be replaced by the formatted float value.

If the user puts "abc12.4" the result will be "0". So it would be better if you use the UITextFieldDelegate method :

textField:shouldChangeCharactersInRange:replacementString:

to check the last key tapped by user. You can just compare it to know if it's a numeric value or a point/comma.

Can