I’m creating a program where the kids must convert a decimal value (I.E. 0.xxxx – precision 4) to a fraction.
I need to know whether a fraction terminates or not, I mean:
1/9 ~ 0.111 but 111/1000 = 0.111
I’m creating a Fraction class, but I have no idea how to distinguish between these two cases.
public class Fraction
{
#region Fields
private int _numerator;
private int _denominator;
#endregion
#region Properties
public int Numerator
{
get { return _numerator;}
set { _numerator = value;}
}
public int Denominator
{
get { return _denominator;}
set { _denominator = value;}
}
public decimal DecimalValue
{
get { return (decimal)_numerator / _denominator; }
}
#endregion
#region Constructors
public Fraction() { }
public Fraction(int numerator, int denominator)
{
this.Numerator = numerator;
this.Denominator = denominator;
}
#endregion
}
Can you help me?
Thanks in advance.
Find the denominator’s prime factorization.
If all the prime factors are either 2 or 5, it will have a finite decimal representation.
If it has a prime factor that is not 2 or 5, then it will be a recurring decimal.
(It works because 10’s prime factors are 2 and 5.)
edit – And check that
numerator % denominatoris not 0, as Stefan H points out.