Convert float to rough part in javascript

We need to convert the calculated value, which can be something like 3.33333000540733337 - 3 1/3. Any of the libraries I've tried, such as https://github.com/peterolson/BigRational.js , will convert this to the most accurate rational number, while I'm only interested in the approximate rational number, up to .01 significant decimal places.

In ruby, we are currently doing Rational (1.333) .rationalize (Rational (0.01)), which gives us 1 integer, 1 is the numerator, and 3 is the denominator.

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

+4
source share
5 answers

You can use such a function 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 as follows:

console.log(rationalize(bigRat(3.33333000540733337),0.01));
+4
source

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

+1
source

.toFixed() , BigRational :

var n = 3.33333000540733337;
m = n.toFixed(2);       // 3.33

.toPrecision() .

: . toFixed() . toPrecision()

+1

. , "". .

  • - .
  • - n, m, (n/m), n m - , m .
  • " ".
  • " ", , (). m = 100, 100-. 1, . 2 ..
  • , , m, (v) m.
  • , rv.
  • (rv/m). (rv modulo m)/m ( )

    v = 3.45.

    1/3, m = 3

    rv = (3.45 * 3) = round (10.35) = 10

    = (10/3) = 3

    = (10 3)/3 = 1/3

0

. , . 3 1/3?

( - ) ( ).

So choose your denominator. Everything follows from this! (Reduce to the lowest conditions - unless you want to look like you were out of elementary school.)

-5
source

All Articles