How to get a single random number in javascript?

Possible duplicate:
Javascript random number generation in a specific range?

Can someone tell me how to get a single-bit random number (1,2,3, .. not 0,1,0,2, .. or 1,0,5,0, ..) using Math.random ( ) or some other way in JavaScript?

+8
source share
5 answers

Math.random() returns a float between 0 and 1 , so just multiply it by 10 and turn it into an integer:

 Math.floor(Math.random() * 10) 

Or something a little shorter:

 ~~(Math.random() * 10) 
+19
source
 var randomnumber=Math.floor(Math.random()*10) 

where 10 dictates that the random number will fall between 0-9.

+4
source

DENIAL OF RESPONSIBILITY:

JavaScript math.rand () is not cryptographically secure, which means that it should NOT be used to generate random numbers associated with a password, PIN, and / or gambling. If this is your use case, please use the web crypto API instead!


If the digit 0 is not included (1-9):

 function randInt() { return Math.floor((Math.random()*9)+1); } 

If the digit 0 (0-9) is turned on:

 function randIntWithZero() { return Math.floor((Math.random()*10)); } 
+3
source

Use this:

 Math.floor((Math.random()*9)+1); 
+1
source
 Math.floor((Math.random()*10)); 

And there goes your random integer from 0 to 10!

+1
source

All Articles