views:

128

answers:

4

Possible Duplicate:
Generating random numbers in Javascript

How do I get a random number between −10 and 10 in JavaScript?

+2  A: 

Using not more than a simple Google search,

var randomnumber=Math.floor(Math.random()*21)-10

Math.random()*21)returns a number between 0 and 20. Substracting 10 would yield a random number between -10 and 10.

My advice: try to Google first, and than ask about the results, e.g.:

What is the best way to get a random number? I've googled and found methods X and Y, and wondered which is best for purpose Z.

Adam Matan
+2  A: 
var min = -10;
var max = 10;
// and the formula is:
var random = Math.floor(Math.random() * (max - min + 1)) + min;
Darin Dimitrov
You closed the question for being: "ambiguous, vague, incomplete, or rhetorical and cannot be reasonably answered in its current form." Yet you answered it here. Can you you explain why?
edeverett
@edeverett, I voted to close as *exact duplicate* to http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript and **not** as *not a real question* but unfortunately it was 3 vs 2 votes. If I was to vote to reopen this question it would be just to close it with the proper reason.
Darin Dimitrov
+4  A: 

jQuery: $.randomBetween(minValue, maxValue);

Akyegane
+1 for the jQuery answer
RC
@RC: http://www.doxdesk.com/img/updates/20091116-so-large.gif
KennyTM
@KennyTM, funny :)
RC
@Kenny, I laughed so much I damn near cried. Surely that's a touch-up job, I can't imagine that voting pattern being real :-)
paxdiablo
@KennyTM, that's so hilarious. Thanks for posting it. I think this is a prime candidate for the daily WTF.
Darin Dimitrov
@RC, @pax, @Darin: (Quoting the reference: http://www.doxdesk.com/updates/2009.html#u20091116-jquery)
KennyTM
-1 For the jQuery overkill here. What's next adding .add() and .sub() to jQuery? >_> People should learn the JavaScript language, not the jQuery library...
Ivo Wetzel
+5  A: 

For example:

var min = -10;
var max = 10;
Math.floor(Math.random() * (max - min + 1) + min)

see http://thepenry.net/jsrandom.php for some comparaison of Math.floor, Math.ceil and Math.round

RC