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.
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With