Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get one digit random number in javascript? [duplicate]

Possible Duplicate:
Generating random numbers in Javascript in a specific range?

Can some one tell me how to get one digit random number(1,2,3,.. not 0.1,0.2,.. or 1.0,5.0,..) using Math.random() or some other way in javascript?

like image 218
Gowsikan Avatar asked Jan 02 '13 13:01

Gowsikan


People also ask

How do you generate a random number in JavaScript?

Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.

How do you generate a random 1 digit number in Java?

For example, to generate a random number between 1 and 10, we can do it like below. ThreadLocalRandom random = ThreadLocalRandom. current(); int rand = random. nextInt(1, 11);

Which line will generate a random number between 1 to 10 in JavaScript?

Math. floor(Math. random() * 10) + 1 //the + 1 makes it so its not 0.


1 Answers

DISCLAIMER:

JavaScript's math.rand() is not cryptographically secure, meaning that this should NOT be used for password, PIN-code and/or gambling related random number generation. If this is your use case, please use the web crypto API instead! (w3c)


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

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

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

function randIntWithZero() {
     return Math.floor((Math.random()*10));
}
like image 71
JohannesB Avatar answered Oct 08 '22 10:10

JohannesB