2

How can I check whether an initialized variable in c++ has integral value or floating point value?

The sample code block is shown below:

int main()
{   
    double number = 9.99;

    if (/*Checks whether the value of the 'number' is an integral*/)
        cout << "The 'number' has an integral value";
    else
        cout << "It's not an integral value" // This condition will true if 'number' has a floating point number
    return 0;

}
6
  • 4
    do you consider 7.0 a integer or a not? Commented Nov 3, 2016 at 13:34
  • Use std::modf en.cppreference.com/w/cpp/numeric/math/modf Possible duplicate of this stackoverflow.com/questions/1521607/… Commented Nov 3, 2016 at 13:36
  • 1
    What is integral value? Do you mean integer value? Commented Nov 3, 2016 at 13:36
  • So if I did wrong with the code, please correct me Commented Nov 3, 2016 at 13:37
  • You could use something simple, for example you could do number == static_cast<int>(number). However that have drawbacks like 7.0 being accepted as an integer. Also with the rounding problems of floating point values, a value could be very close to an integer, but not exactly. Commented Nov 3, 2016 at 13:38

2 Answers 2

3

You're looking for fmod(number, 1.0). If and only if this is exactly 0.0 (no epsilon here), then number is an integral value.

Sign up to request clarification or add additional context in comments.

1 Comment

Good solution, forgot about this. I'm not sure the caveat you introduced though won't fail here as well.
0

How about this?

#include <typeinfo>

// …
int a = 1;
std::cout << typeid(a).name() << '\n';

You could check if typeid(a).name() equals either i or int or whatever else. It depends on your compiler what typeid(a).name() is equal to. But you can check it for int, float and double by checking the output so you can make a condition. Hope it helps

7 Comments

I'm pretty sure the point is assessing whether a float variable is 'integral' in value.
How is this better than std::is_integral ?
I understood that the question is how to check if a variable is an integer or not (in other words what type of variable it is) so that's why I used this method
@SebastianKaczmarek: Yes, that was clear from your answer, but std::is_integral is easier and more portable. It directly tells you true or false; you don't have to guess at strings. (Plus it's compile-time)
@MSalters except then you would have to provide the type.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.