views:

585

answers:

3

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?

A: 

Here's an recipe that converts a float to the closest fraction given a limit for the denominator: http://code.activestate.com/recipes/52317/

Miles
+4  A: 

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.

MSN
+2  A: 

The technique I learned in middle school:

x = 0.33333
10 x = 3.33333

10x - x = 3.3333 - .3333

9x = 3

x = 3 / 9

Reduce 3/9 to 1/3.
abelenky