18

Possible Duplicate:
Generating random numbers in Javascript

I have the following code var randomnumber=Math.floor(Math.random()*101); that generates a random number for me between 1 and 100. What I would like to do is generate a random number between -100 and 100. I am not sure what to do exactly. Any help would be appreciated.

Community
  • 1
  • 1
Cool Guy Yo
  • 5,910
  • 14
  • 59
  • 89

2 Answers2

50

First, generate a random number between 1 - 200 then subtract 100:

var randomNumber = Math.floor(Math.random() * 201) - 100;
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 2
    +1 was just writing the same answer.. – Ben Feb 26 '12 at 04:08
  • Quick question: Can Math.floor() return a value that falls inside [0.99999999999999995, 0.99999999999999999]. Because if it can then the result will be 101 which is outside the given bounds (at least that's what I surmised by running tests on the chrome console). Of course it's a small chance for such a corner case to actually take place (near hardware error). But still its eerie. – XDS Dec 27 '18 at 18:14
  • How about "a + Math.floor(Math.random() * (b – a))" <- this seems more concise. – XDS Dec 27 '18 at 18:21
-3
var randomnumber=Math.floor(Math.random()*200)-100;
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
PC.
  • 6,870
  • 5
  • 36
  • 71