javascriptdecimalfractionsrational-numbers

Convert a decimal number to a fraction / rational number


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".


Solution

  • 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);