Home > Back-end >  Javascript not rounding properly
Javascript not rounding properly

Time:07-18

I made a simple number guessing game in javascript which goes from 1 to 100.
My problem is that everything works, except when I type a decimal number from 100 to 101. I want my code to give me the "Please enter a number from 1 to 100" message then, but it doesn't.
How do I get Javascript to round this properly?

let randomNumber = Math.floor(Math.random() * 100); // Random number

function guess() {
  let inp = document.getElementById("number").value; // Reading input
  let inpRounded = Math.floor(inp);

  // Random number is higher
  if (inpRounded < randomNumber && inpRounded >= 1 && inpRounded <= 100) {
    document.getElementById("result").innerHTML = "Higher";
  }
  // Random number is lower
  else if (inpRounded > randomNumber && inpRounded >= 1 && inpRounded <= 100) {
    document.getElementById("result").innerHTML = "Lower";
    // Input matches random number 
  } else if (inpRounded == randomNumber && inpRounded >= 1 && inpRounded <= 100) {
    document.getElementById("result").innerHTML = "You won!";
  }
  // Input is weird
  else if (inpRounded == null) {
    document.getElementById("result").innerHTML = "Please enter a valid number";
  }
  // Input is lower than 1 or higher than 100
  else if (inpRounded < 1 || inpRounded > 100) {
    document.getElementById("result").innerHTML = "Please enter a number from 1 to 100";
  }
  // Other issue
  else {
    document.getElementById("result").innerHTML = "Error"
  }
}
<h2>Enter a number from 1 to 100</h2>
<input type="number" placeholder="Type your guess here" id="number">
<input type="button" value="Go!" onclick="guess()">
<p id="result"></p>

CodePudding user response:

Just put this code first before you check other things.

  if (inpRounded == null) {
    document.getElementById("result").innerHTML = "Please enter a valid number";
    return;
  }
  if (inpRounded < 1 || inpRounded > 100) {
    document.getElementById("result").innerHTML = "Please enter a number from 1 to 100";
    return;
  }

CodePudding user response:

Don't round the number initially, otherwise you'll lose the decimal information you need when you want to reject values between 100 and 101.

function guess() {
  const value = document.getElementById("number").value; // Reading input
  const numValue = Number(value);
  if (numValue < 1 || numValue > 100) {
    document.getElementById("result").textContent = "Please enter a number from 1 to 100";
    return;
  }
  const inpRounded = Math.floor(numValue);
  // etc
  • Related