-2

Is there any other way to generate a random number from a specific range other than this:

Math.floor(Math.random() * (max - min + 1) + min);
Esko
  • 4,109
  • 2
  • 22
  • 37
  • 2
    Why? Is this not good enough? – deceze Sep 14 '18 at 11:41
  • How is this not working for you? – Luca Kiebel Sep 14 '18 at 11:41
  • 2
    I suspect there's some library somewhere which provides this - but since you can get it correct with just 1 line of code, why not put that in a function of your own if you need to use it a lot? – Robin Zigmond Sep 14 '18 at 11:41
  • Please check https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range – saAction Sep 14 '18 at 11:42
  • I'm sure you can but none will be as efficient as this one line you have here. – Thijs Sep 14 '18 at 11:42
  • Yes. `Math.random() * (max - min) + min` is other than that. – Akaino Sep 14 '18 at 11:42
  • @deceze it is good, i am still a beginner and just practicing and wanted to think of another way – user52068 Sep 14 '18 at 11:44
  • @LucaKiebel it is working, i am still a beginner and just practicing and wanted to think of another way – user52068 Sep 14 '18 at 11:44
  • Well, what you need is a good source of randomness, which is actually a harder problem than you might think. The standard API that Javascript exposes to get a good random number is `Math.random`. So that's all you got to work with, and if you want to extrapolate that to a specific range, this is how you do it. – deceze Sep 14 '18 at 11:45
  • Thank you all... – user52068 Sep 14 '18 at 11:52

1 Answers1

-2

Try this Example

var min = 1;
var max = 100;

Math.floor(Math.random() * (max - min + 1)) + min;
Adeel Ahmed Baloch
  • 672
  • 2
  • 7
  • 15