1

This is a simplified version of the code which removes whole numbers with if statements:

function F1() {
  A = Math.floor((Math.random() * 100 + 1));
  B = Math.floor((Math.random() * 100 + 1));
  Dez = document.getElementById("Dez").innerHTML = A / B;
  if (Math.round(Dez * 10) !== Dez * 10) {
    F1();
  }
  if (Dez <= 0) {
    F1();
  }
  
  if (Dez === 1) {
    F1();
  }

  if (Dez === 2) {
    F1();
  }

//...

  if (Dez === 100) {
    F1();
  }


}
<button onclick="F1()"> New </button>
<label id="Dez"></label>

Is there a shorter way to remove whole numbers with if statements? I want a shorter solution for this part of the code:

if (Dez === 1) {
  F1();
}

if (Dez === 2) {
  F1();
}

if (Dez === 3) {
  F1();
}

...

if (Dez === 100) {
  F1();
}
Save Pain
  • 247
  • 2
  • 9
  • Does this answer your question? [Check if a number has a decimal place/is a whole number](https://stackoverflow.com/questions/2304052/check-if-a-number-has-a-decimal-place-is-a-whole-number) – PM 77-1 Dec 22 '20 at 01:53
  • Not simply a better way, but your code doesn't work. – GetSet Dec 22 '20 at 01:53
  • I find this question very fascinating, but probably not for the reason you think. The possible outcomes of choosing A,B from [1,100] and choosing the quotient that has exactly one non-zero digit after the decimal place are quite interesting and have a fascinating probability distribution. Are you actually attached to that probability distribution? (e.g.: `1.5` is 33x more likely to be generated than `49.5`) Because if you're not, then there's a completely different way to select one of the 170 possible outcomes with uniform distribution. – Wyck Dec 22 '20 at 06:44

1 Answers1

0

You can check if the value is a whole number with % 1 === 0:

function F1() {
  let A, B, Dez;
  do {
    A = Math.floor((Math.random() * 100 + 1));
    B = Math.floor((Math.random() * 100 + 1));
    Dez = A / B;
  } while (Math.round(Dez * 10) !== Dez * 10 || Dez % 1 === 0);
  document.getElementById("Dez").textContent = Dez;
}
document.querySelector('button').addEventListener('click', F1);
<button> New </button>
<label id="Dez"></label>

Also remember to:

  • Declare your variables, like I did - don't implicitly create global variables
  • Only use .innerHTML when inserting HTML markup - otherwise, better to use .textContent, it's faster, safer, and more semantically appropriate
  • Consider avoiding inline handlers, they have some terrible scoping rules and can be difficult to manage, better to use addEventListener instead
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320