Compare floats in Unity

I have 6 InputFields in my scene. Their content type is decimal.

I extract the values ​​from these input fields and check if their sum is 100.02. I enter 16.67 in all of them.

    float fireP   =  float.Parse(firePercentage.text);
    float waterP  =  float.Parse(waterPercentage.text);
    float lightP  =  float.Parse(lightPercentage.text);
    float nightP  =  float.Parse(nightPercentage.text);
    float natureP =  float.Parse(naturePercentage.text);
    float healthP =  float.Parse(healthPercentage.text);

    float total = fireP + waterP + lightP + nightP + natureP + healthP;

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

I get "Not Equal. Your Amount = 100.02" in my console log. Anyway, why could this happen?

+4
source share
2 answers

Nearest floatto 16.67- 16.6700000762939453125.

Nearest floatto 10.02-100.01999664306640625

Adding the first to yourself 5 times is not quite equal to the last, so they will not compare equal ones.

In this particular case, compared to the tolerance in the order of 1e-6, probably the way to go.

+4
source

.

Mathf.Approximately, ,

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

, Decimals, - , EXACT . , , , , . ( 10 ^ 28)

99,99% , , .

: .net

+13

Source: https://habr.com/ru/post/1656946/


All Articles