Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if the result of a float division should be a whole number?

Tags:

c#

unity3d

I want to know if I get an integer or float after division.

if (5.4 / 0.8 ==integer)  // except something that would evaluate as true in this case

{

}
like image 534
writelnMelih Avatar asked Mar 04 '23 23:03

writelnMelih


2 Answers

One way to do it is to use Mathf.Round to find the closest integer to the result and Mathf.Approximately to compare that integer to the result:

float f1 = 0.5;
float f2 = 0.1;
float result = f1/f2;

if (Mathf.Approximately(result, Mathf.Round(result)) {
    Debug.Log("integer result");
}
like image 82
Ruzihm Avatar answered Mar 09 '23 06:03

Ruzihm


Floating point number calculation comes with the precision problem.
For example, 0.3 / 0.1 equals to 2.9999999999999996, not 3.
In order to make a comparison, you'll need to round them and check if the difference is acceptable.

var result = 0.3 / 0.1;
if (Math.Abs(Math.Round(result) - result) < 0.0000001) 
{
    // Do something
}
like image 27
SGKoishi Avatar answered Mar 09 '23 06:03

SGKoishi