Home > OS >  Subtracting a float from another float does not equal a float?
Subtracting a float from another float does not equal a float?

Time:08-28

I am coding with the unity scripting API but I don't think that changes anything.

I have a variable playerMovementScript.rightWallX that is a float and is equal to -20.84.

I then have this line of code:

Debug.Log(-21.24f == playerMovementScript.rightWallX - 0.4f);

It always prints false. I feel like I'm missing something obvious cause I'd like to think I'm not THAT new to coding. Any help would be appreciated.

CodePudding user response:

Floating points not accurate. Use them only for fast calculations. If u want to compare 2 floats use if (Mathf.Approximately(floatA,floatB))

CodePudding user response:

The reason it prints false is because you are using the == operator, which checks if 2 things are equal, therefore since you are doing -21.24f == playerMovementScript.rightWallX - 0.4f, the result is unequal and then it prints false. I am pretty sure you meant =, but we all make mistakes.

  • Related