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?

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;
    }
}

EditorGUI.FloatField

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 {}

For another solution that mimics the original, look here. It has some downsides, though.

float example;
example = Convert.ToSingle(GUILayout.TextField(example.ToString()));

Here is how I solve this. I “clean” the string using regular expression
You will need this at the top of your class:

using System.Text.RegularExpressions;

And here are two methods. One that will clean a float and another an int:

   public static string CleanStringForFloat(string input)
   {
        if(Regex.Match(input,@"^-?[0-9]*(?:\.[0-9]*)?$").Success)
			return input;
		else {
			Debug.Log("Error, Bad Float: " + input);
			return "0";
		}
	}

	public static string CleanStringForInt(string input)
	{
		if(Regex.Match(input,"([-+]?[0-9]+)").Success)
			return input;
		else {
			Debug.Log("Error, Bad Int: " + input);
			return "0";
		}
	}

To use them you would just do this:

string testFloat = Guilayout.TextField(testFloat);
testFloat = CleanStringForFloat(testFloat);