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.
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));
Use the .toFixed()
method before using your library. See http://www.w3schools.com/jsref/jsref_tofixed.asp .
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