How to compare float and double in C++?

C++Server Side ProgrammingProgramming

Comparing floats and double variables depends on what your end goal is. If you want a runnable function without going too much in details and won't have a problem in some inaccurate calculations you can use the following function −


using namespace std;

// Define the error that you can tolerate
#define EPSILON 0.000001

bool areSame(double a, double b) {
   return fabs(a - b) < EPSILON;

int main() {
   double a = 1.005;
   double b = 1.006;
   cout << areSame(a, a);
   cout << areSame(a, b);


This will give the output −


This function takes your tolerance for error and checks if the threshold is greater than the difference between the numbers you're comparing. If you need something much more accurate, you're better off reading this excellent blog       post:

Published on 28-Feb-2018 11:39:41