How to check if divistion returns int?
Hi guys,
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Sep 15, 2008, 4:42 AM
In the case of integers or decimals, I'd only use a 'try' statement if there's a possibility that the divisor could be zero at runtime - if it is, then an exception will be thrown which you can catch.
One good thing about floating point (float and double types) is that they never throw exceptions. Instead they have special values such as positive and negative infinity or NaN (not a number) which you get if the divisor is zero.
MystX JonesPosted Sep 14, 2008, 8:12 PM
Hi again,
Sorry, i had the code and everything typed out, but didnt show in my post for some reason 0.o my apologies
Basically i was using a try statement that tried to divide one int by the second int and put the answer into a third int (with a catch statement to catch any errors) but it seemed to truncate the value before assigning it.
Anyhow, the first method you showed will work fine, thanks alot
AlanPosted Sep 14, 2008, 6:39 AM
Well, it depends what you're dividing.
If you're dividing integers, then an easy way to check that the result is an exact integer is to use the remainder operator(%). For example:
int i1 = 12;
int i2 = 3;
int i3 = i1/i2;
int i4 = i1 % i2;
if (i4 == 0)
{
Console.WriteLine("Result is a whole number");
}
else
{
Console.WriteLine("Result is not a whole number");
}
If you're dividing floating point or decimal numbers, then you can use the Math.Truncate() method as the following example illustrates:
double d1 = 12.0;
double d2 = 3.0;
double d3 = d1/d2;
double d4 = d3 - Math.Truncate(d3);
if (d4 == 0.0)
{
Console.WriteLine("Result is a whole number");
}
else
{
Console.WriteLine("Result is not a whole number");
}