1

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

Best method use Math object for example to take the random number of:

  • [a, b] (double - integer) (2 cases)
  • (a, b) (double - integer)
  • [a, b) (double - integer)
  • (a, b] (double - integer)

Anybody can help me? Thanks!

Community
  • 1
  • 1
Johan Gosh
  • 131
  • 1
  • 7

3 Answers3

1

I guess this is what you're looking for:

var rand = function(a,b){
    return a+Math.round((b-a)*Math.random());
}
var r = rand(5,10);
console.log(r);
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
1
Math.extendedRandom = function(a,b,excludeA,excludeB, round)
{
    var start = a;
    var end = b;
    if(excludeA)
        start++;
    if(excludeB)
        end--;

    var res = (end-start) * Math.random();
    return start + (round ? Math.floor(res) : res);
};
David Rettenbacher
  • 5,088
  • 2
  • 36
  • 45
0

The simplest case is the third one, which is already the implementation of Math.random in JavaScript.

The first case is answered by Trevor in this question. Make sure to read the other answers and comments, though, to get a clear understanding of the implications.

Likewise, the fourth case is answered by nickf in that same question.

The second case could be handled by a variation of Trevor's answer:

function zero_exclusive_random(){
  var r = Math.random();
  return r == 0 ? zero_exclusive_random() : r;
}
Community
  • 1
  • 1
Brandan
  • 14,735
  • 3
  • 56
  • 71