-2
float num1 = 1;

if (num1 == 1)
{
     printf("Yes, it is equal!!\n");
}
else
{
     printf("No, it is not equal\n");
}

output --> Yes, it is equal!

whereas

float num1 = 1.2;

if (num1 == 1.2)
{
    printf("Yes, it is equal!!\n");
}
else
{
    printf("No, it is not equal\n");
}

output --> No, it is not equal

but why? Please explain in detail.

2 Answers2

4

In spite of your title, there is no comparison with any int value.

num == 1.2 compares the float value in num with the double value of 1.2.

When 1.2 is converted to double in your C implementation, it is converted to the nearest representable value. Since your C implementation uses a binary-based system for floating-point, it cannot exactly represent 1.2, and there is a small error in the conversion.

In float num1 = 1.2;, the double value resulting from 1.2 is converted again, this time to float. Since float has less precision than double, there is even more error. The result is that the float num1 is not equal to the double 1.2.

Thus, the comparison num1 == 1.2 evaluates to false.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
3

Be very careful in exact comparison of float numbers. No all values can be presented as float exactly, because not all values can be presented as finite sum of components being power (positive or negative) of 2. The same problem is about double.

There is no good and universal solution for your problem, it strongly depends to kind of possible values, expected accuracy etc.

Probably you should move into integer values, for example by multyplying your floats by some power of 10, then convert (round) to int, and - finally - compare.

VillageTech
  • 1,968
  • 8
  • 18