Search Unity

Converting string to float, or int (Preferably float)

Discussion in 'Scripting' started by Flynn, Aug 21, 2009.

  1. Flynn

    Flynn

    Joined:
    May 24, 2009
    Posts:
    311
    My goal is to create a system where the user can enter a number (preferably even with decimals) into a GUI text box. The idea is that the string is converted to a float, and this float is used for other purposes...


    Here is the code I am trying:

    Code (csharp):
    1. var a = "";
    2. var b = 0;
    3. a = GUI.TextField(Rect(10,120,40,20),a);
    4. b = parseInt(a);

    First of all, if the code worked, it would only give me an int - so is there is any other way of converting the string so that it returns a float?

    Second of all, using this method, I get the following error:


    Any help?
     
  2. gtjuggler

    gtjuggler

    Joined:
    Nov 13, 2008
    Posts:
    238
    This works just fine:

    Code (csharp):
    1.  
    2. var thestring : String;
    3. var thefloat : float = 0.0;
    4.  
    5. function Start() {
    6.     thestring = "1234.2";
    7. }
    8.  
    9. function OnGUI () {
    10.     thestring = GUI.TextField (Rect (10, 10, 200, 20), thestring, 25);
    11.     thefloat = parseFloat(thestring);
    12.     print(thefloat);
    13. }
    14.  
     
  3. HiggyB

    HiggyB

    Unity Product Evangelist

    Joined:
    Dec 8, 2006
    Posts:
    6,183
    And please use the search as this comes up at least once a week or so. Searching the Scripting section only with the keyword "convert" turned up these two threads from last week, both of which discuss string-to-int and string-to-float techniques (and vice versa):

    http://forum.unity3d.com/viewtopic.php?t=30012
    http://forum.unity3d.com/viewtopic.php?t=30075

    And yeah, parseFloat is the ticket. :)



    *Yes, that is the rally call for me to get the Scripting FAQ started and this is prime material!
     
  4. Flynn

    Flynn

    Joined:
    May 24, 2009
    Posts:
    311
    Thanks!

    It works perfectly! :D

    I apologize, higgyB, I will try the search next time.