Create a random number between -100 and 100 in JavaScript?

36,012

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

var randomNumber = Math.floor(Math.random() * 201) - 100;
Share:
36,012

Related videos on Youtube

Cool Guy Yo
Author by

Cool Guy Yo

reading, cooking, gardening, and making websites is what I like to do.

Updated on July 09, 2022

Comments

  • Cool Guy Yo
    Cool Guy Yo almost 2 years

    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.

    • Lightness Races in Orbit
      Lightness Races in Orbit about 12 years
      You could start by reading your Javascript function reference.
  • Ben
    Ben about 12 years
    +1 was just writing the same answer..
  • Ben
    Ben about 12 years
    Shouldn't it be 201 to include 100?
  • XDS
    XDS over 5 years
    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
    XDS over 5 years
    How about "a + Math.floor(Math.random() * (b – a))" <- this seems more concise.