convert decimal number to fraction in javascript or closest fraction

后端 未结 10 1579
温柔的废话
温柔的废话 2020-12-05 16:12

So i want to be able to convert any decimal number into fraction. In both forms such as one without remainder like this: 3/5 or with remainder: 3 1/4

10条回答
  •  一生所求
    2020-12-05 16:42

    I get very poor results using the GCD approach. I got much better results using an iterative approach.

    For example, here is a very crude approach that zeros in on a fraction from a decimal:

    function toFraction(x, tolerance) {
        if (x == 0) return [0, 1];
        if (x < 0) x = -x;
        if (!tolerance) tolerance = 0.0001;
        var num = 1, den = 1;
    
        function iterate() {
            var R = num/den;
            if (Math.abs((R-x)/x) < tolerance) return;
    
            if (R < x) num++;
            else den++;
            iterate();
        }
    
        iterate();
        return [num, den];
    }
    

    The idea is you increment the numerator if you are below the value, and increment the denominator if you are above the value.

提交回复
热议问题