Skip to content Skip to sidebar Skip to footer

Random Number Js Min Max

I'm trying to get random number between 2 numbers from input in JavaScript. When I put numbers instead of max.value and min.value it works, but not with variable. I can't understan

Solution 1:

The problem is that the value of input elements are always strings. When you write max.value - min.value, JavaScript coerces the values to numbers because of the subtraction operator. BUT when you write 0.3 + "8" the result is "0.38" instead of "8.3". That's why the original code gives strange values, max.value never gets added but appended. Here is a possibility how to fix it: coerce the strings into numbers first with the uniary + operator (or use parseInt):

functiongenRanNumb() {
  var vMin = +min.value;
  var vMax = +max.value;
  var generated = Math.floor(Math.random()*(vMax - vMin + 1) + vMin);
  demo.innerText = generated;
}
<inputtype="text"id="min"><inputtype="text"id="max"><buttonid="btn"onclick="genRanNumb()">button</button><pid="demo"></p>

Solution 2:

I think the matter is your inputs are text and your random wants int values The solution is to surrond your variable with parseFloat(yourvariable) in javascript. in your case you have :

functiongenRanNumb() {
  document.getElementById('demo').innerHTML=Math.floor(Math.random()*(parseFloat(max.value)-parseFloat(min.value)+1)+parseFloat(min.value));
}

Hope it answer to your question.

For better readability and best compatibility, you should write it like this:

functiongenRanNumb() {
  var max = parseFloat(document.getElementById("max").value,10),
      min = parseFloat(document.getElementById("min").value,10);

  document.getElementById('demo').innerHTML=Math.floor(Math.random()*(max-min+1)+min);
}

Solution 3:

Alternative to get the random number from min to max

let makeGuess = function(guess){
    let min = 1;
    let max = 5;   
    let randomNumber = Math.floor(Math.random() * (max - min + 1)) + minreturn guess === randomNumber;

}
console.log(makeGuess(1));

Solution 4:

Your random number logic is correct. You just need to retrieve the values from the textboxes, which are strings, and then parse them as integers.

functiongenRanNumb() {
  var min = parseInt(document.getElementById('min').value, 10);
  var max = parseInt(document.getElementById('max').value, 10);
  document.getElementById('demo').innerHTML=Math.floor(Math.random()*(max-min+1)+min);
}
<inputtype="text"id="min"><inputtype="text"id="max"><buttonid="btn"onclick="genRanNumb()">button</button><pid="demo"></p>

Solution 5:

The probleme is your value are string so when you do:

(max.value-min.value+1)+(min.value)

it like to do, for example, 6" + "5" so "65"

So try it:

<script>functiongenRanNumb() {
     document.getElementById('demo').innerHTML=Math.floor(Math.random()*(parseInt(max.value-min.value+1))+parseInt(min.value));
   }

</script>

Post a Comment for "Random Number Js Min Max"