Convert a decimal number to a fraction / rational number

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

    A little googling with the term "decimal to fraction js" the first yielded this:

    http://wildreason.com/wildreason-blog/2010/javascript-convert-a-decimal-into-a-simplified-fraction/

    It seems to work:

    http://jsfiddle.net/VKfHH/

    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

提交回复
热议问题