Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert decimal number to fraction in javascript or closest fraction

Tags:

javascript

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.

  • Calculate amount of digits after decimals.
  • multiply by 10 with power of the amount before number.
  • then somehow find greatest common factor.

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;
like image 311
Muhammad Umer Avatar asked May 09 '14 23:05

Muhammad Umer


People also ask

How do you display fractions in JavaScript?

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.

How do I convert a decimal number to a fraction?

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.

What is 0.6 as a fractions?

Answer: Fractional form of 0.6 is 3/5 Let's convert 0.6 into a fraction.


2 Answers

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.

like image 155
Sani Singh Huttunen Avatar answered Oct 31 '22 02:10

Sani Singh Huttunen


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

like image 34
Xotic750 Avatar answered Oct 31 '22 03:10

Xotic750