Convert a decimal number to a fraction / rational number

Anderson Green picture Anderson Green · Feb 9, 2013 · Viewed 27.4k times · Source

In JavaScript, is there any way to convert a decimal number (such as 0.0002) to a fraction represented as a string (such as "2/10000")?

If a function called decimalToFraction had been written for this purpose, then decimalToFraction(0.0002) would return the string "2/10000".

Answer

Trent Earl picture Trent Earl · Feb 9, 2013

You can use Erik Garrison's fraction.js library to do that and more fractional operations.

var f = new Fraction(2, 10000);
console.log(f.numerator + '/' + f.denominator);

To to do .003 you can just do

var f = new Fraction(.003);
console.log(f.numerator + '/' + f.denominator);