Search Unity

Convert a float to a string.

Discussion in 'Scripting' started by Jessy, Dec 23, 2007.

  1. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
    How do I do it? (JavaScript)
     
  2. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    Doesn't .ToString () work?


    Code (csharp):
    1. function Start ()
    2. {
    3.     var myFloat : float = 5.5;
    4.     var myString : String = myFloat.ToString ();
    5.     throw myString;
    6. }
     
  3. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
    It did. I have no idea what I did not do right, because I could have sworn I did what you wrote. Anyway, it's working now. Hooray! Thanks a ton.
     
  4. bigkahuna

    bigkahuna

    Joined:
    Apr 30, 2006
    Posts:
    5,434
    Code (csharp):
    1. throw myString;
    Huh, I've never seen that used before. So "throw" can be used to remove variables? Is it worth doing?
     
  5. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    I think it just prints a message. It's similar to Debug.LogError (), i think.
     
  6. bronxbomber92

    bronxbomber92

    Joined:
    Nov 11, 2006
    Posts:
    888
    throw is for catching exceptions, errors, ect.. (this is checking if the string is null or not). It's like C's assert or C++'s throw/catch.
     
  7. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Here's how you use throw:

    Code (csharp):
    1.     // Try to read an integer value from a string
    2.     try {
    3.         var newSize = parseInt(levelSizeString);
    4.         // If parsing worked but the values are too silly
    5.         if (newSize < 2 || newSize > 99) {
    6.             throw "Bad data";
    7.         }
    8.     }
    9.     // If reading the value didn't work, do nothing
    10.     catch (err) {
    11.         print (err.Message);
    12.         return;
    13.     }
    14.     // Otherwise use the string's value
    15.     LevelEditor.setSize = newSize;
    16.  
    (Adapted from one of my recent scripts.) You can use it to generate exceptions, like in those cases where something technically works, but you want it to fail anyway. In this case, parseInt will generate an exception if it tries to parse something like "226saQQ!!!" because of the non-numerical data, but I also wanted to fail for certain legal values too.

    --Eric
     
  8. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    Thanks for clarifying it.