Search code examples
floating-pointunity-game-engineunityscript

float division in unityscript


Why does this code give 536870912 as output and not 536870911.5?

var z : double = 1073741823.0 / 2.0;
Debug.Log(z.ToString("F15"));

And how can I get it to output 536870911.5? This seems odd to me...


Solution

  • You can get it with the below using C#:

    double test = 1073741823.0d / 2.0d; // = 536870911.5
    Debug.Log(test);
    

    And in UnityScript, you just need to add the d's

    var test : double = 1073741823.0d / 2.0d; // = 536870911.5
    Debug.Log(test);
    

    Without the double notation, UnityScript is parsing the numbers as some other type. (Most likely an int)

    The below does NOT work because the interpreter isn't casting them correctly:

    var test : double = 1073741823.0 / 2.0; // = 536870912
    Debug.Log(test);
    

    Looks to me like it's reading: double = int / int;


    Very interesting. This is another reason why I encourage developers to move to C#.