1
<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.

4 Answers 4

4

@Ojas Kale, first things first. Min and max are being passed strings. Try parsing them into integers first.

getRandomArbitrary(parseInt(document.getElementById('low').value),parseInt(document.getElementById('high').value));

Also I please modify the getRandom function as below. No need to round the sum right?

function getRandomArbitrary(min, max) {

    var r = Math.floor(Math.random() * (max - min + 1) )+ min;
    document.getElementById('demo').innerHTML = r; 
}
Sign up to request clarification or add additional context in comments.

Comments

3

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>

1 Comment

Perfect. Works fine Now. Thanks a lot.
1
Math.floor(Math.random() * max) + min 

1 Comment

the problem is not with the logic of finding random number. problem lies somewhere when I pass the value from html page.
0
var min = (your minimum number value);
var max = (your maximum number value);
var myRandom = Math.floor(Math.random() * max) + min;

To get random number as an integer between two number, you can use the function; Thanks to this function you will generate an integer between min and max

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.