convert decimal number to fraction in javascript or closest fraction

后端 未结 10 1598
温柔的废话
温柔的废话 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

    The tricky bit is not letting floating points get carried away.

    Converting a number to a string restrains the trailing digits,

    especially when you have a decimal with an integer, like 1.0625.

    You can round off clumsy fractions, by passing a precision parameter.

    Often you want to force a rounded value up, so a third parameter can specify that.

    (e.g.; If you are using a precision of 1/64, the smallest return for a non-zero number will be 1/64, and not 0.)

    Math.gcd= function(a, b){
        if(b) return Math.gcd(b, a%b);
        return Math.abs(a);
    }
    Math.fraction= function(n, prec, up){
        var s= String(n), 
        p= s.indexOf('.');
        if(p== -1) return s;
    
        var i= Math.floor(n) || '', 
        dec= s.substring(p), 
        m= prec || Math.pow(10, dec.length-1), 
        num= up=== 1? Math.ceil(dec*m): Math.round(dec*m), 
        den= m, 
        g= Math.gcd(num, den);
    
        if(den/g==1) return String(i+(num/g));
    
        if(i) i= i+' and  ';
        return i+ String(num/g)+'/'+String(den/g);
    }
    

    Math.roundFraction(.3435,64); value: (String) 11/32

提交回复
热议问题