Search Unity

How can I convert Int to String?

Discussion in 'Scripting' started by Bright_sky, Sep 6, 2011.

  1. Bright_sky

    Bright_sky

    Joined:
    Aug 28, 2011
    Posts:
    22
    How to convert int to string in JavaScript?
     
  2. giancamati

    giancamati

    Joined:
    Aug 4, 2010
    Posts:
    518
    if you have a variable like

    var i : int = 5;
    var s: string;

    s = ""+ i;

    javascript is an interpreted language and it will convert the integer directly into the correspondent string.

    Hope this helps.
    :)
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Use .ToString().

    Javascript in Unity is compiled, not interpreted (as well as not really being Javascript), and in any case that doesn't have anything to do with the conversion. It's better to use ToString rather than string concatenation anyway.

    --Eric
     
  4. giancamati

    giancamati

    Joined:
    Aug 4, 2010
    Posts:
    518
    For the sake of my curiosity.... what's the difference? :)
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    It's a little faster, has less memory allocation, and it's better (more obvious) code.

    --Eric
     
  6. Fenrisul

    Fenrisul

    Joined:
    Jan 2, 2010
    Posts:
    618
    ToString( ) also gives you more options as to formatting when you need it as well.

    like ToString("f5") will return a string equivalent of a float out to 5-decimal places. But yea essentially


    "" + variable;

    Allocates a string for the ""
    Performs a ToString( ) on the variable (allocating another string)
    then concatenates them
     
  7. HrC123

    HrC123

    Joined:
    Feb 2, 2011
    Posts:
    140
    is it possible convert string to float or integer?
    C#
     
  8. markhula

    markhula

    Joined:
    Sep 3, 2011
    Posts:
    630
    atoi?
     
  9. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    float.parse ("5");
    int.parse ("5");
     
  10. bdev

    bdev

    Joined:
    Jan 4, 2011
    Posts:
    656
    :) miss c

    if you want to avoid exceptions for non parsable stuff:

    var f : float;

    if( float.TryParse( "0.2", f ) ){
    // f will be 0.2
    }else{
    // could not parse string f will be 0.0
    }