8

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

I fetch values from these input fields and check if their sum is equal to 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's equal");
   }
   else
   {
     Debug.Log(" Not equal. Your sum is = " + total);
   }

I am getting " Not equal. Your sum is = 100.02" in my console log. Anyways has any idea why this might be happening ?

Ruzihm
  • 19,749
  • 5
  • 36
  • 48
Sameer Hussain
  • 2,421
  • 8
  • 23
  • 41

2 Answers2

24

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

derHugo
  • 83,094
  • 9
  • 75
  • 115
Riaan Walters
  • 2,587
  • 2
  • 18
  • 30
  • This works right. I had already tried this. But I wanted to know why exactly does this happen. Thanks for the reply, it will help everyone stuck on this issue but @Snoop Dog 's answer is why it is really happening. – Sameer Hussain Oct 06 '16 at 14:26
7

The nearest float to 16.67 is 16.6700000762939453125.

The nearest float to 100.02 is 100.01999664306640625

Adding the former to itself 5 times is not exactly equal to the latter, so they will not compare equal.

In this particular case, comparing with a tolerance in the order of 1e-6 is probably the way to go.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825