x


how to use a float in a GUI.TextField?

Using C#, in the OnGUI function I just have something simple like this:

someFloatMemberVariable = float.Parse(GUI.TextField(someRect, someFloatMemberVariable.ToString()));

someFloatMemberVariable is of type float and is initialized to say 1.5, but when I type in the textfield another float, the decimal won't show up, and I always get a FormatException.

Any thoughts?

more ▼

asked Mar 01 '11 at 04:32 PM

jacksmash2012 gravatar image

jacksmash2012
312 32 43 55

I think when you get as far as typing "12." then the decimal point would be stripped by the parsing operation. You would have the same problem with trailing zeroes after the decimal. I suggest you let the user type into a string variable, then parse that into your float, rather than continuously converting the float to a string. Not sure about the format exception though.

Mar 01 '11 at 05:30 PM yoyo
(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

The trick here is to use a string format for the variable which forces the decimal point. Like so:

public float Length;

void OnGUI()
{
    string lengthText = GUILayout.TextField(Length.ToString("0.00"));

    float newLength;
    if (float.TryParse(lengthText, out newLength))
    {
        Length = newLength;
    }
}

EDIT: It is also possible by adding a bool to store if a . is entered. Downside is that it needs a further variable:

public float Length;
bool _isLengthDecimal;

void OnGUI()
{
    string lengthText = GUILayout.TextField(Length.ToString() + (_isLengthDecimal ? "." : ""));
    _isLengthDecimal = lengthText.EndsWith(".");

    float newLength;
    if (float.TryParse(lengthText, out newLength))
    {
        Length = newLength;
    }
}
more ▼

answered Mar 22 '12 at 10:07 AM

stfx gravatar image

stfx
96 3 4 6

(comments are locked)
10|3000 characters needed characters left

when you trying to parse to float and parse value is not valid ("3.5g", "4.k3", ...), it throw exception you can write follow

try {
     someFloatMemberVariable = float.Parse(GUI.TextField(rect, someFloatMemberVariable.ToString()));
} catch {}
more ▼

answered Mar 01 '11 at 05:11 PM

mrde gravatar image

mrde
466 7 7 17

Yes, I know about try/catch and how it works. That doesn't solve my problem though.

Mar 01 '11 at 05:21 PM jacksmash2012
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3668
x181

asked: Mar 01 '11 at 04:32 PM

Seen: 2002 times

Last Updated: Mar 22 '12 at 10:55 AM