- Home /
The question is answered, right answer was accepted
Unity thinks that 14 = 15?
Hello,
Debug.Log ((int) ((0.4875f + 0.4125f - 0.75f) * 100f));
Why does Unity tell me 14? Any way to fix that? I give you that numbers as a result from other formulas, so you can count it easily, I... I just don't know what to think.
Btw Unity converts -15 float into -15 int normally, but for some odd reason it thinks that 15 float is 14 int.
Answer by tanoshimi · Jun 28, 2015 at 06:15 PM
Simple casting a float to (int) loses the fractional part due to integer truncation The result of your calculation is something like 14.99997f, so (int)14.99997f = 14.
If you want the answer 15, try Mathf.Round() instead.
This illustrates the point. Run both of these scripts and notice the number of decimal places in the added decimal number. The scripts are identical except one has 1 less decimal place on the added constant in the debug.
using UnityEngine;
public class Test : $$anonymous$$onoBehaviour
{
float one;
void Start ()
{
one = ((0.4875f + 0.4125f - 0.75f) * 100f);
}
void Update ()
{
Debug.Log (one);
Debug.Log ((int)(one + 0.000001f));
}
}
using UnityEngine;
public class Test : $$anonymous$$onoBehaviour
{
float one;
void Start ()
{
one = ((0.4875f + 0.4125f - 0.75f) * 100f);
}
void Update ()
{
Debug.Log (one);
Debug.Log ((int)(one + 0.00001f));
}
}
But it's not 14.99997f, it's 15.00000000000(infinite 0s)f It's 15. Fifteen.
How did you get 14.99997?
There is ALWAYS floating point error in a float.
It says its 15.0000000000000000 but its likely not.
$$anonymous$$y little script demo will illustrate to you how far you can expect a float to be out.
As tanoshimi explained, an int will ALWAYS round down, so 14.99997 will become 14.
Rounding up rounds to int that has a larger value
1.5 -> 2
-1.5 -> -1
Rounding down rounds to int that has a smaller value
1.5 -> 1
-1.5 -> -2
Rounding to 0 rounds down for positive numbers and up for negative numbers
1.5 -> 1
-1.5 -> -1