How to check if divistion returns int?
Hi guys,
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
AlanRank #669 · 3.6K reputationPosted Sep 14, 2008, 2:39 AM EDT
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");
}
MystX Jones5 reputationPosted Sep 14, 2008, 4:12 PM EDT
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
AlanRank #669 · 3.6K reputationPosted Sep 15, 2008, 12:42 AM EDT
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.