convert decimal number to fraction in javascript o

2020-01-31 02:46发布

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.

what i was doing is this..

lets say i have number .3435.

  • Calculate amount of digits after decimals.
  • multiply by 10 with power of the amount before number.
  • then somehow find greatest common factor.

Now i don't know how to find GCF. And nor i know how to implement logic to find fraction that represents a number closely or in remainder form if exact fraction doesn't exists.

code i have so far: (testing)

x = 34/35;
a = x - x.toFixed();
tens = (10).pow(a.toString().length - 2);

numerator = tens * x;
denominator = tens;

标签: javascript
9条回答
ら.Afraid
2楼-- · 2020-01-31 03:16

I had researched all over the website and I did combine all code into one, Here you go!

function fra_to_dec(num){
    var test=(String(num).split('.')[1] || []).length;
    var num=(num*(10**Number(test)))
    var den=(10**Number(test))
    function reduce(numerator,denominator){
        var gcd = function gcd(a,b) {
            return b ? gcd(b, a%b) : a;
        };
        gcd = gcd(numerator,denominator);
        return [numerator/gcd, denominator/gcd];
    }
    return (reduce(num,den)[0]+"/"+reduce(num,den)[1])
}

This code is very easy to use! You can even put number in this function!

查看更多
Root(大扎)
3楼-- · 2020-01-31 03:16

I came up with this for 16ths

function getfract(theNum){
    var input=theNum.toString();
    var whole = input.split(".")[0];
    var rem = input.split(".")[1] * .1;
    return(whole + " " + Math.round(rem * 16) + "/16");
}
查看更多
beautiful°
4楼-- · 2020-01-31 03:17

One quick and easy way of doing it is

getFraction = (decimal) => {
  for(var denominator = 1; (decimal * denominator) % 1 !== 0; denominator++);
  return {numerator: decimal * denominator, denominator: denominator};
}
查看更多
登录 后发表回答