Generate Random Whole Numbers within a Range

My testing for generating a random whole number within a range... 🤞

While the solution here works, it just loops until it gets a random number that is lower than the max, so not sure if this is the best solution. But it passes the test. 😉

Demo

function randomNumRange(myMin, myMax) {
  var result_html = document.getElementById("result");

  var random_num = Math.floor(Math.random() * myMax) + myMin;
  while(random_num > myMax) {
    var random_num = Math.floor(Math.random() * myMax) + myMin;
  }
  result_html.innerHTML = random_num;
}

HTML

<div id='result' class='mb-3 alert alert-primary'>..</div>
<button onclick='randomNumRange(1,10);' class='btn btn-primary mb-1'>Random 1 - 10</button>
<button onclick='randomNumRange(50,100);' class='btn btn-primary mb-1'>Random 50 - 100</button>

Result

..

External Link for Generate Random Whole Numbers within a Range

Other Items in javascript
Page Views

This page has been viewed 59 times.

Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

❤👩‍💻🕹