So i want to be able to convert any decimal number into fraction. In both forms such as one without remainder like this: 3/5
or with remainder: 3 1/4
.
what i was doing is this..
lets say i have number .3435.
Now i don't know how to find GCF. And nor i know how to implement logic to find fraction that represents a number closely or in remainder form if exact fraction doesn't exists.
code i have so far: (testing)
x = 34/35;
a = x - x.toFixed();
tens = (10).pow(a.toString().length - 2);
numerator = tens * x;
denominator = tens;
Fractions don't exist in JavaScript, but you can rewrite them as division problems using the division operator. Note that the resulting number is always converted to decimals — just like with a calculator. Improper fractions use the division operator in the same way.
To convert a decimal to a fraction, place the decimal number over its place value. For example, in 0.6, the six is in the tenths place, so we place 6 over 10 to create the equivalent fraction, 6/10. If needed, simplify the fraction.
Answer: Fractional form of 0.6 is 3/5 Let's convert 0.6 into a fraction.
Your first 2 steps are reasonable.
But what you should do is for the numerator and denominator calculate the Greatest Common Divisor (GCD) and then divide the numerator and denominator with that divisor to get the fraction you want.
GCD is rather easy to calculate. Here is Euclid's algorithm:
var gcd = function(a, b) {
if (!b) return a;
return gcd(b, a % b);
};
Edit
I've added a fully working JSFiddle.
Unless you are willing to work on developing something yourself then I would suggest using a library that someone has already put effort into, like fraction.js
Javascript
var frac = new Fraction(0.3435);
console.log(frac.toString());
Output
687/2000
On jsFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With