I need to know how to do this procedure.
calculation1: 1/4 = 0,25
calculation2: 1/8 = 0,125
calculation3: 47/183 = 0,25683060109289617486338797814207......
calculation4: 58/889 = 0,06524184476940382452193475815523......
calculation5: 1/5 = 0,2
The results of calculations 1, 2 and 5 will give a short result, no periods or and endless string of digits. The results of calculations 3 and 4 are very long and complicated.
How can I check which calculation is an “easy one” and gives a “short” result.
I tried this and it gave a wrong result for sure…
like you can see, the results of the calculations have the datatype double in my application.
static bool IsInt(double x)
{
try
{
int y = Int32.Parse(x.ToString());
return true;
}
catch
{
return false;
}
}
I hope it is clear what I’m asking.
If after reducing the fraction as much as possible, the denominator can be expressed as a power of 2 multiplied by a power of 5, then the decimal representation terminates. Otherwise it repeats indefinitely.
You could test if your division is “good” as follows:
See it working online: ideone
Note that I am passing the numerator and denominator separately to the method. If you do the division first, then pass the result to your method, you lose precision due to floating point representation error.
Also for production code you should check that
b != 0because it is not allowed to divide by 0. Without the check the above code would go into an infinite loop.