C# – Format Repeating Decimal as a Fraction


I need to convert decimal values to their fractional equivalents, similar to this previous question.

I'm using the code posted in one of the answers as a starting point since it mostly does what I need it to do.

string ToMixedFraction(decimal x) {
int whole = (int) x;
int denominator = 64;
int numerator = (int)( (x - whole) * denominator );

if (numerator == 0) 
    return whole.ToString();
while ( numerator % 2 == 0 ) // simplify fraction
    numerator /= 2;
    denominator /=2;
return string.Format("{0} {1}/{2}", whole, numerator, denominator);

As I said, this code works fine for the most part, but I need to take common repeating decimal values (.3333333) and display that to the user as 1/3.

Does anyone happen to know how this might be possible to do?

Best Solution

From http://mathforum.org/library/drmath/view/61579.html

Take the number of digits in the repeating part as the numerator, take 9 repeating with the same number of digits and reduce the fraction.

E.g., .3 repeating is the same as 3/9. Reduce by dividing both sides by the gcd (3 in this case) and you get 1/3.

You'll need to do some extra math if you can extract a repeating decimal from a terminating decimal, e.g. .133333333.