Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a float to an approximate fraction in javascript

We need to convert a calculated value which might be something like 3.33333000540733337 to 3 1/3. Any of the libraries I've tried such as https://github.com/peterolson/BigRational.js will convert that to the most accurate rational number whereas I'm only concerned with the approximate rational number, to .01 significant decimals.

In ruby we currently do Rational(1.333).rationalize(Rational(0.01)) which gives us 1 as whole number, 1 as numerator and 3 as denominator.

Any thoughts on an algorithm that might help would be great.

like image 889
dstarh Avatar asked Oct 20 '22 23:10

dstarh


2 Answers

You can use a function like this using the https://github.com/peterolson/BigRational.js library:

function rationalize(rational, epsilon) {
    var denominator = 0;
    var numerator;
    var error;

    do {
        denominator++;
        numerator = Math.round((rational.numerator * denominator) / rational.denominator);
        error = Math.abs(rational.minus(numerator / denominator));
    } while (error > epsilon);
    return bigRat(numerator, denominator);
}

It will return a bigRat object. You can check your example with this:

console.log(rationalize(bigRat(3.33333000540733337),0.01));
like image 184
Juan Sánchez Avatar answered Oct 30 '22 15:10

Juan Sánchez


Use the .toFixed() method before using your library. See http://www.w3schools.com/jsref/jsref_tofixed.asp .

like image 36
StackSlave Avatar answered Oct 30 '22 15:10

StackSlave