- Home /
How to Get a Textfield to Accept only numbers and periods.
Currently I'm using this section of code:
if (chr < '0' || chr > '9' && chr != '.') {
Event.current.character = '\0';
}
However, I've come to realize that I can't place a period into the text field with or without this code. I can't use commas either. Long story short I'm getting frustrated not being able to place/display float values in these fields.
Answer by DaveA · Jan 11, 2013 at 02:02 AM
Something like this: http://answers.unity3d.com/questions/40103/text-field--inputting-numbers-only.html
As elegant as that may seem, that won't allow me to place periods in the text field. I would like players to be able to select a value for a given item, and it would automatically adjust the cost, however, I would like them to be able to use decimals. Currently I can't find a way to allow periods to be input into the textfield.
This is great link to beautiful example and deserves appreciation. All you have to do then is
a) Learn and understand the code b) Tweek it to your needs.
And this is what this portal is all about. Helping people to learn and steer them into right direction. And then when you gain you should help others on their stuff. Just expecting complete scripts and then pasting (and not even pasting in wright place) does nothing.
Bonus: All you have to do is use float.tryParse if you want floating points.
As I mentioned in my comment on that answer, the code won't actually work, so it's not really a good example. See my answer here for the best way I've found so far (the Regex example will also work, but has usability issues as described by $$anonymous$$olix in the comment on my answer).
Answer by Eric5h5 · Jan 11, 2013 at 05:00 AM
It's just a matter of fixing the logic by using parentheses, since the expression is evaluated left to right, and elements inside parentheses are grouped:
if ( (chr < '0' || chr > '9') && chr != '.') {
Event.current.character = '\0';
}
However that would still allow multiple periods, which is probably not desirable, so that could be fixed (assuming that your string variable is called "myString"):
if ( ((chr < '0' || chr > '9') && chr != '.') || (chr == '.' && myString.Contains(".")) ) {
Event.current.character = '\0';
}
As mentioned previously, even without that section of code (nice catch by the way) I can't put periods inside a text field. Just generic textfield with no intercept code, still can't type a period there.
Your answer
Follow this Question
Related Questions
Problem with Android Keyboard/TextField 1 Answer
Background of GUI.TextField disappears when using a GUIStyle 2 Answers
Select all text in a GUI.TextField? 1 Answer
GUI.TextField problem, won't update var. 0 Answers
gui text and password field 1 Answer