Convert a decimal number to a fraction / rational number

前端 未结 11 1825
情歌与酒
情歌与酒 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:08

    This may be a little old but the code that was posted fails on 0 values I have fixed that error and will post the updated code below

    //function to get highest common factor of two numbers (a fraction)
    function HCF(u, v) { 
        var U = u, V = v
        while (true) {
            if (!(U%=V)) return V
            if (!(V%=U)) return U 
        } 
    }
    //convert a decimal into a fraction
    function fraction(decimal){
    
        if(!decimal){
            decimal=this;
        }
        whole = String(decimal).split('.')[0];
        decimal = parseFloat("."+String(decimal).split('.')[1]);
        num = "1";
        for(z=0; z

提交回复
热议问题