Home > OS >  How to reduce negative fractions in Javascript
How to reduce negative fractions in Javascript

Time:02-22

I have seen this question but it doesn't work for negative numbers or numbers with ( ) prefixes.

Here's what I want.

-20/8 = -5/2  
 28/-6 = -14/3  
-30/-4 = 15/2  
34/12 = 17/6
 40/6 = 20/3
32/ 64 = 1/2

CodePudding user response:

Thanks to @Bravo I got this piece of code that works!

function reduce(num, den) {
    if (num.startsWith(" ")) {
        num = num.substring(1);
    }
    if (den.startsWith(" ")) {
        den = den.substring(1);
    }
    const neg = num < 0 != den < 0;
    num = Math.abs(num);
    den = Math.abs(den);
    var gcd = function gcd(a, b) {
        return !b ? a : gcd(b, a % b);
    };
    var g = gcd(num, den);
    return [neg ? "-"   num / g : num / g, den / g];
}

It works very well as expected.

CodePudding user response:

Try with that code :

function reduce(numerator,denominator,toString=false){
    var gcd = function gcd(a,b){
      return b ? gcd(b, a%b) : a;
    };
    gcd = gcd(numerator,denominator);
    var temp_num = numerator / gcd;
    var temp_deno= denominator / gcd;

    if(temp_deno < 0 ){
        temp_deno *= -1;
        temp_num *= -1;
    }

    var result = [temp_num, temp_deno];
    if(toString){
        return result.toString().replace(',','/');
    }
    return result;
  }

// Test : true for returning string
console.log(reduce(-20,8,true));    //-5/2  
console.log(reduce( 28,-6,true));   //-14/3 
console.log(reduce(-30,-4,true));   //15/2
console.log(reduce(34,12,true));    //17/6
console.log(reduce( 40,6,true));    //20/3
console.log(reduce(32, 64,true));   //1/2

  • Related