13

Possible Duplicate:
Generating random whole numbers in JavaScript in a specific range

How can I get one-digit random numbers (1, 2, 3, ..., not 0.1, 0.2, ... or 1.0, 5.0, ...) using Math.random() or some other way in JavaScript?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gowsikan
  • 5,571
  • 8
  • 33
  • 43
  • 1
    possible duplicates: [Generating random numbers in Javascript in a specific range?](http://stackoverflow.com/questions/1527803/), [Random between two numbers in Javascript](http://stackoverflow.com/questions/4959975), [Random number between -10 and 10 in JavaScript](http://stackoverflow.com/questions/3594177), – mellamokb Jan 02 '13 at 13:27
  • Should 0 (zero) be included or not? [JohannesB's answer](https://stackoverflow.com/questions/14122894/how-can-i-get-a-one-digit-random-number-in-javascript/14123012#14123012) covers both possibilities. – Peter Mortensen May 10 '22 at 13:30

5 Answers5

27

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)
Blender
  • 289,723
  • 53
  • 439
  • 496
7

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));
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JohannesB
  • 1,995
  • 21
  • 35
4
var randomnumber=Math.floor(Math.random()*10)

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

Paul Collingwood
  • 9,053
  • 3
  • 23
  • 36
1

Use this:

Math.floor((Math.random()*9)+1);
Tanzeel Kazi
  • 3,797
  • 1
  • 17
  • 22
1
Math.floor((Math.random()*10));

And there goes your random integer between 0 and 10!

gopi1410
  • 6,567
  • 9
  • 41
  • 75