Why can't we compare a float value with some numerical value

Viewed 79

I tried the below code i assigned a float value to variable and i compared it with a floating point value but it did not gave the desired output. Here as a==13.30 is true i thought it will print "a" instead it prints "5"

#include<iostream>
using namespace std;
int main()
{
    float a=13.30;
    if(a==13.30)
    cout<<a;
    else
    cout<<"5";

}

output is "5" not "a"

2 Answers

13.30 is a double. Try comparing against 13.30f.

0.30 cannot be represented exactly and since double has a higher precision, it is not an exact match.

Ofcourse you can simply compare float value with some numerical value , but just because you can , it doesn't mean you should. It's classical example of that . There are many problems regarding storing exact floating point value in memory , due to hardware restrictions , this issue regarding storing exact floating point value in memory exist in virtually all the programming languages and platform . A better way to equating floating point values is checking if the difference of two values that you need to compare is less than some other very small number . In your code , you can implement that as ,

#include <iostream>
using namespace std;
const double EPSILON = 1e-5;
int main()
{
  float a = 13.30;
  if (abs(a - 13.30) < EPSILON)
    cout << a;
  else
    cout << "5";
}

Now , this code will output 13.30 , here EPSILON is used as a very small double value to compare with the difference . To know more about why this issue is prevalent read , Is-floating-point-math-broken and Why are floating point numbers inaccurate

Related