How to check whether a floating-point variable is an integer (has no fractional part) in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>        // std::floor, std::fabs

// -----------------------------------------------------------------------------
// Checks whether a double represents an integer value.
// We compare the number to its floored version. If the difference is zero
// (within a tiny tolerance), the value is effectively an integer.
// -----------------------------------------------------------------------------
bool isInteger(double value)
{
    // A small tolerance helps avoid issues with floating‑point precision.
    const double epsilon = 1e-12;

    // floor(value) gives the largest integer <= value.
    double floored = std::floor(value);

    // If the absolute difference is extremely small, treat it as an integer.
    return std::fabs(value - floored) < epsilon;
}

// -----------------------------------------------------------------------------
// Prints a message describing whether the given double is an integer.
// -----------------------------------------------------------------------------
void printCheck(double value)
{
    std::cout << "Checking value: " << value << '\n';

    if (isInteger(value)) {
        std::cout << "Result: The value contains an integer.\n\n";
    }
    else {
        std::cout << "Result: The value contains a floating‑point number.\n\n";
    }
}

// -----------------------------------------------------------------------------
// Entry point.
// -----------------------------------------------------------------------------
int main()
{
    // Demonstration values.
    double a = 42.0;      // integer-like
    double b = 42.00000000001; // floating-point due to tiny fraction
    double c = 89.0000000000001; // integer-like
    double d = -7.0;      // negative integer-like
    double e = 3.14;      // floating-point

    // Run checks.
    printCheck(a);
    printCheck(b);
    printCheck(c);
    printCheck(d);
    printCheck(d);
}


/*
run:

Checking value: 42
Result: The value contains an integer.

Checking value: 42
Result: The value contains a floating‑point number.

Checking value: 89
Result: The value contains an integer.

Checking value: -7
Result: The value contains an integer.

Checking value: -7
Result: The value contains an integer.

*/

 



answered Jan 29, 2024 by avibootz
edited Sep 10 by avibootz

Related questions

...