Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

cast int to float in javascript

Discussion in 'Editor & General Support' started by j7caiman, Sep 3, 2010.

  1. j7caiman

    j7caiman

    Joined:
    Aug 11, 2010
    Posts:
    13
    This is an embarrassing question but:
    How do I cast an int to a float in javascript?

    In C/C++, this would be:
    int a = 10;
    float b = (float)a;

    For now I am using:
    var a = 10;
    var b = 20;

    /*...*/

    var c:float = a;
    var d:float = b;

    var e:float = c/d;

    But I don't want to create a new variable just to cast something.

    More generally, how does one cast objects/primitives in javascript? I could not find a good resource on this anywhere.

    Thanks,
    Jon
     
  2. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    Casting in UnityScript is done through <variable name> as <classname>
    so

    a as float

    for example.
    though the cast in that direction should normally work implicitely too
     
  3. j7caiman

    j7caiman

    Joined:
    Aug 11, 2010
    Posts:
    13
    I tried that earlier and got:
    Assets/Height Map/DynamicallyMakePlanes.js(370,41): BCE0006: 'int' is a value type. The 'as' operator can only be used with reference types.

    I think it doesn't work since int is a primitive?
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    In Javascript it would be

    var a = 10;
    var b : float = a;

    --Eric
     
  5. podperson

    podperson

    Joined:
    Jun 6, 2006
    Posts:
    1,371
    heh I log in for a completely unrelated purpose and learn something useful ("as"). Thanks dreamora. (I really need to go update my JavaScript/UnityScript article, but I think someone else did a better one...)
     
  6. j7caiman

    j7caiman

    Joined:
    Aug 11, 2010
    Posts:
    13
    Eric:

    Maybe this is nitpicky, but say you have:

    var a = 10;
    var b = 20;
    var c:float = a/b;


    You would get c == 0.
    Is the only way to get around this to do:

    var a = 10;
    var b = 20;
    var af:float = a;
    var bf:float = b;

    var c:float = af/bf;
     
  7. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    var c : float = parseFloat(a) / b;

    or

    var c : float = (a+0.0) / b;

    --Eric
     
  8. j7caiman

    j7caiman

    Joined:
    Aug 11, 2010
    Posts:
    13
    Thanks! I appreciate the fix Eric.
     
  9. Grim_Darknight

    Grim_Darknight

    Joined:
    Nov 22, 2012
    Posts:
    6
    for my project I have gotten this to work out pretty simply:

    #pragma strict

    var af =0.0;

    var ai = 0;

    function Update ()
    {
    ai=af;
    }