0

I need a function with a decimal number as input (parameter). The function should turn the fraction of the number and output it as decimal number.

I think, in my use caces the numerator can always be 1. For example I have the fraction 1/4

and would like to get the output 4/1 (same as 4).

If anyone has an other idea how to solve it, please answer as well.

I am happy about every answer

Adolf Weii
  • 23
  • 6
  • 2
    Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan Jun 03 '20 at 08:09
  • But DO beware: https://stackoverflow.com/questions/11695618/dealing-with-float-precision-in-javascript – mplungjan Jun 03 '20 at 08:10

1 Answers1

0

As log as all of your fractions have the numerator of 1 the function is simply 1/fraction: (1/f)-1 = 1/(1/f) = f.

Whenever you have something that has not a numerator of 1, the result will be different but also not possible with using a "deciaml"/float input, just because of rules of math. The decimal point-number 0.25 is equal to 1/4, 2/8, 4/16, ... This makes it impossible (without saving the fraction) to get back from only the reduced decimal point-number to the "original" fraction.

function denominator(fraction){
  return 1/fraction;
}

// demo only
const test_fractions = ["1/2", "1/3", "1/4", "1/9", "1/35", "2/8"];
for(let i = 0; i < test_fractions.length; i++){
  let f = test_fractions[i].split("/");
  f = parseInt(f[0])/parseInt(f[1]);
  console.log("The denominator of", test_fractions[i], "=", f, "is", denominator(f));
}
miile7
  • 2,547
  • 3
  • 23
  • 38