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;

}
yasmikash
  • 157
  • 2
  • 14
  • 4
    do you consider 7.0 a integer or a not? – NathanOliver Nov 03 '16 at 13:34
  • Use std::modf http://en.cppreference.com/w/cpp/numeric/math/modf Possible duplicate of this http://stackoverflow.com/questions/1521607/check-double-variable-if-it-contains-an-integer-and-not-floating-point – DejaVuSansMono Nov 03 '16 at 13:36
  • 1
    What is integral value? Do you mean integer value? – mbaros Nov 03 '16 at 13:36
  • So if I did wrong with the code, please correct me – yasmikash Nov 03 '16 at 13:37
  • You could use something simple, for example you could do `number == static_cast(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. – Some programmer dude Nov 03 '16 at 13:38
  • A `double` (or a `float`) is most definitely a floating point number. It will be represented in memory as a float, either in 4 or 8 bytes. It cannot be an integer. If you say `double x = 1;` this cannot be and will not be a `0...01` in memory. –  Nov 03 '16 at 13:41

2 Answers2

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • Good solution, forgot about this. I'm not sure the caveat you introduced though won't fail here as well. – kabanus Nov 03 '16 at 14:43
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

Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38