My code converts repeating decimals to fractions. It works but I am interested in feedback on how I could improve and/or simplify it?
jsFiddle: http://jsfiddle.net/tfgTu/
<script>
// Repeating decimal
// 21.83(35745857)
var decimal = 21.8335745857
// Total length of the decimal
var decimalLength = 10;
// Length of the decimal before the repeating part
var decimalBeforeRepeatLength = 2;
// 10 to the total length of the decimal
var power1 = Math.pow(10, decimalLength);
// 10 to the length of the decimal before the repeating part
var power2 = Math.pow(10, decimalBeforeRepeatLength);
var finalPower = power1 - power2;
var decimal1 = decimal * power1;
var decimal2 = parseInt(decimal * power2);
var finalDecimal = decimal1 - decimal2;
var output = simplifyFraction(0, finalDecimal, finalPower);
document.write(output[1] + " / " + output[2]);
// Finds the greatest common divisor of 2 non-zero integers
// a = integer 1
// b = integer 2
function greatestCommonDivisor(a, b) {
if (b === 0) {
return a;
}
return greatestCommonDivisor(b, (a % b));
}
// Simplifies all forms of fractions
// Does not change form of fraction
// i = number
// n = numerator
// d = denominator
function simplifyFraction(i, n, d) {
var gcd = greatestCommonDivisor(n, d);
if (Math.abs(i) > 0 && n >= d) { // If mixed number AND improper fraction, assume the user wants a simplified mixed number
if (i < 0) {
n *= -1;
}
var temp = improperFractionToMixedNumber(n, d);
return [temp[0] + i, temp[1] / gcd, temp[2] / gcd];
}
return [i, n / gcd, d / gcd];
}
</script>