Monday, October 17, 2022

[FIXED] how to check if a float number is an integer in cpp?

Issue

For example 14.2 is not an integer but 14.0 is an integer in a mathematical perspective. What I've tried to do is the following, let n be a long double, so to check if it's an integer I compared it to its integer form:

if (n == (int) n) 
{
    // n is an integer
}

It all looks perfect but when I applied it, it didn't work, and when i debugged the program I discovered that the long double number is never a whole number; it's not 14.0 instead it's 14.0000000000000000000002, the last 2 is added by the compiler.

Does someone know how to fix it?


Solution

The cleanest approach is to use floor() and not concern yourself with casting to integer types which makes the false assumption that there will be no overflow in converting a floating-point value to integer. For large floats that's obviously not true.

#include <iostream>
#include <cmath> // This is where the overloaded versions of floor() are.


bool is_whole(double d){
    return d==floor(d);
}

int main() {
    double x{14.0};
    double y{14.2};
    double z{-173.5};
    
    std::cout << is_whole(14.0) << '\n';    
    std::cout << is_whole(14.2) << '\n';
    std::cout << is_whole(-123.4) << '\n';
    std::cout << is_whole(-120394794.0) << '\n';
    std::cout << is_whole(-120394794.44) << '\n';
    std::cout << is_whole(3681726.0) << '\n';
    
    return 0;
}

Expected Output:

1
0
0
1
0
1


Answered By - Persixty
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.