Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good way to check if a double is an integer in C#? [duplicate]

Possible Duplicate:
How to determine if a decimal/double is an integer?

I have a variable of type double and am wanting to check whether it is an integer.

At the moment I have

public bool CheckIfInteger(double number)
{
    return number.ToString().Contains(".") == false;
}

Is there a better way?

UPDATE: Sorry I didn't realise the potential for confusion, by integer I meant the mathematical definiton of integer, that is the natural numbers together with the negatives of the non-zero natural numbers.

like image 301
Simon Avatar asked Nov 02 '10 11:11

Simon


People also ask

How do you know if a double is int?

This checks if the rounded-down value of the double is the same as the double. Your variable could have an int or double value and Math. floor(variable) always has an int value, so if your variable is equal to Math. floor(variable) then it must have an int value.

How do you check if a value is an integer in C?

int isdigit( int arg ); Function isdigit() takes a single argument in the form of an integer and returns the value of type int . Even though, isdigit() takes integer as an argument, character is passed to the function. Internally, the character is converted to its ASCII value for the check.

Can double store integer in C?

Short answer is "no" - the range of values an int can represent and that a double can represent are implementation defined - but a double certainly cannot support every integral value in the range it can represent.

Can a double be an integer?

An int is an integer, which you might remember from math is a whole number. A double is a number with a decimal. The number 1 is an integer while the number 1.0 is a double.


1 Answers

return Math.Truncate(number) == number;

As mentioned in the comments, you might need to take account of the fact that a double representation of your number might not be an exact integer. In that case you'll need to allow for some margin-of-error:

double diff = Math.Abs(Math.Truncate(number) - number);
return (diff < 0.0000001) || (diff > 0.9999999);
like image 69
LukeH Avatar answered Oct 03 '22 15:10

LukeH