How to check if a double variable contains an integer and not a floating point or a floating-point tolerance in C

1 Answer

0 votes
#include <stdio.h>
#include <math.h>
#include <stdbool.h>

// If a double may contain tiny rounding errors (e.g., 3.0000000001), we use tolerance:

bool is_integer_tolerance(double x, double eps) {
    
    return fabs(x - round(x)) < eps;  // true if x is close enough to an integer
}

int main() {
    double x = 982317.0000000001;
    double eps = 1e-9; // tolerance for floating‑point noise

    if (is_integer_tolerance(x, eps)) {
        puts("yes");
    } else {
        puts("no");
    }

    return 0;
}


/*
run:

yes

*/

 



answered Sep 10 by avibootz

Related questions

...