Why two different results?!

Hi. Could someone explain to me why i have two different results?!
In case 1 the result is 8 and in case 2 the result is 7. (Unity2021.3.0f1)

private void Start()
    {
        //case 1
        float a = transform.position.z;
        Debug.Log(a); //(12.11f)
        float b = 1.73f;
        Debug.Log(Mathf.CeilToInt(a / b)); //(8)

        //case 2
        float c = 12.11f;
        Debug.Log(c); //(12.11f)
        float d = 1.73f;
        Debug.Log(Mathf.CeilToInt(c / d)); //(7)      
    }

Welcome to floating point!

https://starmanta.gitbooks.io/unitytipsredux/content/floating-point.html

Perhaps Mathf.Round() would be more suitable? I am not sure, since I don’t know your use case.

Try this:

Debug.Log(a.ToString("F8");
Debug.Log(c.ToString("F8");

If i set transform.position.z to 12.11 in the code or in the inspector then both results are 7 but if i move object by hand using the snap option to exacly position 12.11 the results are different. Looks like moving the object and snapping don’t show the correct location in the inspector at it is in reality.

both 12.11000000

Unfortunately 12.11 is an impossible number to represent as a binary floating point value. That is going to cause some discrepancies when various systems need to convert to/from it.

If i delete 12.11 in the inspector and put a value 12.11 by hand then it’s working OK

I’ll say it one more time, as everybody has been saying above.

12.11 is not necessarily equal to 12.11

The sooner you get over that and reason about how rounding and precision works, the sooner you will stop spinning around a non-issue.

I highly recommend you read the link I posted above from Star Manta.

When you perform operations on hardcoded numbers in C# (“c / d” in your 2nd case), the operation is evaluated during compilation and replaced by the hardcoded result value in the compiled binary. The catch is that the C# compiler used by Unity seems to perform compile-time operations using doubles instead of floats, which have higher precision and thus produce slightly different values.

Sorry I mistyped. See this example: https://dotnetfiddle.net/CqnLal

And with your code:

Debug.Log(a.ToString("G9");
Debug.Log(c.ToString("G9");