2

I have a variable from:

double result = myList.Count / mySeptum;

I want to do the following:

if( result == int ) {
      //Do Something...
} 
else{
      //Do another thing...
}

How can I do this?

I also tried this, but it didn't work:

if ( result%10 == 0 ){
...
}

In an example:

private void button2_Click(object sender, EventArgs e)
{
    int r = 10;
    int l = 2;
    double d = r / l;

    if (d % 10 == 0)
    {
        Console.WriteLine("INTEGER");
    }
    else
    {
        Console.WriteLine("DOUBLE");
    }
}
c-chavez
  • 7,237
  • 5
  • 35
  • 49
Portostor
  • 23
  • 4

4 Answers4

0

For example:

double d = 1.0;
bool isInt = d == (int)d;

modulo:

double d = 1.0;
bool isInt = d % 1 == 0;
Gowtham Alan
  • 234
  • 3
  • 15
0

In general a floating point number on a computer can not represent every real number but only some discrete values. Thus, only for a few integers it will be possible that a double can be mathematically identical to an integer value. For most integers the closest double will be off by a small amount. So if you are looking for exact matches this will not work.

However, what you could do is to convert your double into an integer an check if the difference between the double and the integer is small enough:

double d = 1.5;
int i = (int) d;

double diff = d - i;

if (diff < 1.0e-6)
{
     std::cout << "number is close to integer" << std::endl;
}
AchimGuetlein
  • 501
  • 3
  • 9
0

How to check my double variable is an integer or not?

From a C point of view (as post was originally tagged):
(I am certain C# has equivalent functions.)

To determine if a double is a whole number, use modf() to return the fractional part.

#include <math.h>

double x = ....;

double ipart;
if (isfinite(x) && modf(x, &ipart) == 0.0) {
  // value is a whole number
  ....

To further test if it is in int range

  if (ipart >= INT_MIN && ipart <= INT_MAX) {
     int i = (int) ipart; 

To check for wider integer types, we need some trickery to insure to no round-off error when forming the limits. Code takes advantage that INT..._MAX are Mersenne numbers

  #define INT64_MAX_P1 ((INT64_MAX/2 + 1)*2.0)

  if (ipart >= INT64_MIN && ipart < INT64_MAX_P1) {
     int64_t i64 = (int64_t) ipart; 
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
-1

Try with typeOf:

if (myInt.GetType() == typeof(int))
E.Benedos
  • 1,585
  • 14
  • 41