I have a java class I wrote for java that represents rational numbers using the Bignteger class for the numerator and denominator. Besides basic operations, it also includes an instance method for converting to a repeating decimal and a static method for the reverse converson. Here they are:
public String toRepeatingDecimalString()
{
if (den.equals(BigInteger.ONE))
return num.toString();
BigInteger d = new BigInteger(den.toString());
long pow2 = 0;
long pow5 = 0;
BigInteger two = new BigInteger("2");
BigInteger five = new BigInteger("5");
BigInteger ten = two.multiply(five);
while (d.mod(two).equals(BigInteger.ZERO)) {
d = d.divide(two);
pow2++;
}
while (d.mod(five).equals(BigInteger.ZERO)) {
d = d.divide(five);
pow5++;
}
long nonrep = Math.max(pow2, pow5);
String decimal = num.abs().divide(den).toString() + ".";
if (num.signum() < 0) decimal = "-" + decimal;
BigInteger rem = num.abs().mod(den);
for (long i = 0; i < nonrep; i++) {
rem = rem.multiply(ten);
decimal += rem.divide(den).toString();
rem = rem.mod(den);
}
if (!rem.equals(BigInteger.ZERO)) {
BigInteger stop = new BigInteger(rem.toString());
decimal += "[";
rem = rem.multiply(ten);
decimal += rem.divide(den).toString();
rem = rem.mod(den);
while (!rem.equals(stop)) {
rem = rem.multiply(ten);
decimal += rem.divide(den).toString();
rem = rem.mod(den);
}
decimal += "]";
}
return decimal;
}
and
public static Fraction fromRepeatingDecimalString(String repDecStr)
{
int index = repDecStr.indexOf('.');
if (index == -1)
return new Fraction(new BigInteger(repDecStr), BigInteger.ONE);
else {
int sign = 1;
if (repDecStr.startsWith("-"))
sign = -1;
BigInteger intPart = (sign == 1 ? new BigInteger(repDecStr.substring(0,index)) :
(new BigInteger(repDecStr.substring(1,index))).negate());
String fpart = repDecStr.substring(index+1);
BigInteger TEN = new BigInteger("10");
index = fpart.indexOf('[');
if (index == -1) {
BigInteger d = TEN.pow(fpart.length());
if (sign == 1)
return new Fraction(intPart.multiply(d).add(new BigInteger(fpart)),d);
else
return new Fraction(intPart.multiply(d).subtract(new BigInteger(fpart)),d);
}
else {
if(!(fpart.endsWith("]")))
throw new NumberFormatException();
String nonrep = fpart.substring(0,index);
String rep = fpart.substring(index+1,fpart.length()-1);
BigInteger part1 = TEN.pow(nonrep.length());
BigInteger part2 = TEN.pow(rep.length()).subtract(BigInteger.ONE);
BigInteger full = part1.multiply(part2);
if (nonrep.equals(""))
nonrep = "0";
if (sign == 1)
return new Fraction(full.multiply(intPart).add(part2.multiply(new BigInteger(nonrep)))
.add(new BigInteger(rep)),full);
else
return new Fraction(full.multiply(intPart).subtract(part2.multiply(new BigInteger(nonrep)))
.subtract(new BigInteger(rep)),full);
}
}
}
The fraction is reduced to lowest terms by the class constructor.