How to create a random number with js from a range starting from 1?

I used this code to generate a random number using js:

var max = 10; Math.floor( Math.random() * ( max + 1 ) ); 

From what I understand, it will generate a number from 0 to 10, but what if I want to create a random number from 1 to 10? or from 5 to 10?

+4
source share
3 answers

try the following:

 function getRandomInt(min, max){ return Math.floor(Math.random() * (max - min + 1)) + min; } 
+9
source

You do from 0 to 9, then add it to the result.

+1
source

If you want to start with x instead of 0, then:

  • Subtract x from max
  • Do the rest as usual
  • Add x to result
+1
source

All Articles