Convert a decimal number to a fraction / rational number

前端 未结 11 1826
情歌与酒
情歌与酒 2020-12-01 16:36

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\")?

I

11条回答
  •  天命终不由人
    2020-12-01 17:01

    There is a very simple solution using string representation of numbers

        string = function(f){ // returns string representation of an object or number
            return f+"";
        }
        fPart = function(f){ // returns the fraction part (the part after the '.') of a number
            str = string(f);
            return str.indexOf(".")<0?"0":str.substring(str.indexOf(".") + 1);
        }
        wPart = function(f){ // returns the integer part (the part before the '.') of a number
            str = string(f);
            return str.indexOf(".")<0?str:str.substring(0, str.indexOf(".")); // possibility 1
            //return string(f - parseInt(fPart(f))); // just substract the fPart
        }
    
        power = function(base, exp){
            var tmp = base;
            while(exp>1){
                base*=tmp;
                --exp;
            }
            return base;
        }
    
        getFraction = function(f){ // the function
            var denominator = power(10, fPart(f).length), numerator = parseInt(fPart(f)) + parseInt(wPart(f))*denominator;
            return "[ " + numerator + ", " + denominator + "]";
        }
    
        console.log(getFraction(987.23));
    

    which will just check how many numbers are in the fraction and then expands the fraction of f/1 until f is an integer. This can lead to huge fractions, so you can reduce it by dividing both numerator and denominator by the greatest common divisor of both, e.g.

        // greatest common divisor brute force
        gcd = function(x,y){
            for(var i = Math.min(x, y);i>0;i--) if(!(x%i||y%i)) return i;
            return 1;
        }
    

提交回复
热议问题