How to generate a random number in a given range in javascript VER 2

published: 30 Sep 2022

2 min read

Another method with a seed

Input: 2 cardinal numbers

Output: a random cardinal number in the range [min, max] inclusive

function getRandomNumberInRange(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);  
  return Math.floor(random() * (max - min + 1)) + min;
}

function random() {
  let seed = new Date().getTime();
  var x = Math.sin(seed) * 10000;
  return x - Math.floor(x);
}

getRandomNumberInRange(3, 20);

How to generate a random number in a given range  in javascript VER 2 | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript
Check out what's on in the tag: nodejs, javascript, numbers

TipsAndTricksta

I love coding, I love coding tips & tricks, code snippets and javascript