ochj1ch ochj1ch - 5 months ago 18
HTML Question

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 understand how does random in js work, in other programming languages I know it's easy done like random(min,max) so I totally don't understand why is it so hard in JS. Thank you.



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

<input type="text" id="min">
<input type="text" id="max">
<button id="btn" onclick="genRanNumb()">button</button>
<p id="demo"></p>




Answer

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 :

function genRanNumb() {
  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:

function genRanNumb() {
  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);
}