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;
Related videos on Youtube
Author by
Cool Guy Yo
reading, cooking, gardening, and making websites is what I like to do.
Updated on July 09, 2022Comments
-
Cool Guy Yo almost 2 years
Possible Duplicate:
Generating random numbers in JavascriptI 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 about 12 yearsYou could start by reading your Javascript function reference.
-
-
Ben about 12 years+1 was just writing the same answer..
-
Ben about 12 yearsShouldn't it be 201 to include 100?
-
XDS over 5 yearsQuick 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 over 5 yearsHow about "a + Math.floor(Math.random() * (b – a))" <- this seems more concise.