user14482437
user14482437

Reputation:

Javascript (html) Math.random() range not working

i would like to generate a random number between "lowestnum" and "highestnum". they are inputs by the user.

i used this code in my but the number generated is not within the range

var secret = Math.floor(Math.random()*(highestnum-lowestnum+1)+lowestnum); 

for example: i typed in lowest=4, highest=6, secret should be either 4/5/6. but in fact, number generated is 0/1/2. i found out that it is because 6-4 is 2, and it will only generate 0 to 2, which is the difference between the number, but not any number between 4 to 6

edited! updated clearer question

these are what its inside html

<input id="highestnum" type="text" name="highestnum"> ```

and inside javascript is this 
```var lowestnum = document.getElementById("lowestnum").value; 
var highestnum = document.getElementById("highestnum").value; 
var secret = Math.floor(Math.random()*(highestnum-lowestnum+1)+lowestnum);```

Upvotes: 0

Views: 458

Answers (2)

Noa
Noa

Reputation: 1216

Try this.

function randomNumber() 
{

    var lowestnum =  parseInt(document.getElementById("lowestnum").value);
    var highestnum = parseInt(document.getElementById("highestnum").value);
    secret=Math.floor(Math.random() * (Math.abs(highestnum - lowestnum) + 1) + lowestnum); 
    console.log(secret);
}

window.onload = function() {

document.addEventListener('keyup', function(event) {
    var lowestnum =  document.getElementById("lowestnum");
    var highestnum = document.getElementById("highestnum");
if (event.target === lowestnum || event.target === highestnum ) {
    if(lowestnum.value.length > 0 && highestnum .value.length>0){
        document.getElementById("button").removeAttribute("disabled");
    }
    else{
        document.getElementById("button").setAttribute("disabled","true");
    }
}

}, false);

}
<input type="number" id="lowestnum">
<input type="number" id="highestnum">
<button type="button" disabled id="button">generate</button>

UPDATE just parse it to int

Upvotes: 2

Robin
Robin

Reputation: 5427

According to MDN

Getting a random number between 0 (inclusive) and 1 (exclusive):

function getRandom() {
  return Math.random();
}

Getting a random number between two values:

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

Getting a random integer between two values:

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}

Getting a random integer between two values, inclusive:

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is inclusive 
}

Upvotes: 1

Related Questions