Ojas Kale Ojas Kale - 5 months ago 9
Javascript Question

Random Numbers JavaScript

<head>
<script>
function getRandomArbitrary(min, max) {

var r = Math.floor(Math.random() * (max - min + 1) + min);
document.getElementById('demo').innerHTML = r;
}
</script>
</head>

<body>
<h1>randomize</h1>
a: <input type="text" id='low'><br>
b: <input type="text" id='high'><br>
<button onclick="getRandomArbitrary(document.getElementById('low').value,document.getElementById('high').value)">Get</button>


<div id='demo'></demo>
</body>


I have above code, through which I am trying to generate random number between range given in texts a and b. when I manually pass the values to this function (say 10,15) it works properly (giving, say 13). but when I press the button and ask it to get value from text and calculate the random number in that range it fails to do so and calculates number which is out of range(sometimes).

I have spent a lot of time on it and couldn't see what is the problem. Please help me.

Answer

Cast the value as Number and then pass to function

Unary plus (+), The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.

function getRandomArbitrary(min, max) {
  var r = Math.floor(Math.random() * (max - min + 1) + min);
  document.getElementById('demo').innerHTML = r;
}
<h1>randomize</h1>
a:
<input type="text" id='low'>
<br>b:
<input type="text" id='high'>
<br>
<button onclick="getRandomArbitrary(+document.getElementById('low').value,+document.getElementById('high').value)">Get</button>
<div id='demo'></div>