- Home /
The question is answered, right answer was accepted
int myX = (int)transform.position.x;
Can someone explain me why the following lines of code :
int myX = (int)transform.position.x;
int myZ = (int)transform.position.z;
Debug.Log("trxy= " + transform.position.x + ", " + transform.position.z + " myxz= " + myX + ", " + myZ);
are tracing me those results :
trxz= 25, 12 myxz= 25, 11
trxz= 30, 13 myxz= 30, 12 ...
but on 40 traces, several are ok, example :
trxy= 15, 27 myxz= 15, 27
trxy= 27, 21 myxz= 27, 21 ...
i'm loosing time on that one !
So, computers are pretty good at faking it, but they're actually not all that precise about "floating point" numbers. For example, what you think is "11.0" might actually be closer to "10.99999".
When you cast a float to an int, the computer always rounds down. That 10.99999 would just become 10.
Programmers usually get around this in two ways:
Ins$$anonymous$$d of expecting exact equality, look for "fuzzy equality" within some tolerance.
Be aware that int conversions will truncate; if that's a problem, you can specify your rounding with Unity's $$anonymous$$athf.Round and RoundToInt.
I'm hesitant to let this through the moderation queue because it's a frequently asked question. It's not a bad question, we're just trying to cut down on the number of duplicate threads in this area of the site. If you have anything else to add, feel free to comment here; if not, I'll drop the question from the queue in a little while.
If you can't find help, here, you can always try the forums or look up some tutorials online.
Answer by robertbu · Aug 12, 2014 at 04:33 AM
It is likely the ToString() method for integers rounds to some decimal place, but the casting to an int truncates. So if the real value of transform.position.z was 11.99999999999999, the string would be 12, and the integer cast of that value would be 11. To get around the problem do:
int myX = Mathf.RoundToInt(transform.position.x);
int myZ = Mathf.RoundToInt(transform.position.z);
Follow this Question
Related Questions
OpenFeint float scores 2 Answers
Why are floats not accessing my inputted values? 1 Answer
[Closed] Cannot convert types? 2 Answers
Checking an increasing number 1 Answer
Rounded particle motion 0 Answers