Compare floats in Unity

You indeed have a floating point issue.

In unity you can and should use Mathf.Approximately, it’s a utility function they built exactly for this purpose

Try this

if (Mathf.Approximately(total, 100.02f))
{
    Debug.Log("It's equal");
}
else
{
   Debug.Log(" Not equal. Your sum is = " + total);
}

Additionally, as a side note, you should work with Decimals if you plan on doing any calculations where having the EXACT number is of critical importance. It is a slightly bigger data structure, and thus slower, but it is designed not to have floating point issues. (or accurate to 10^28 at least)

For 99.99% of cases floats and doubles are enough, given that you compare them properly.

A more in-depth explanation can be found here : Difference between decimal float and double in .net

Leave a Comment