JavaScript Random Positive or Negative Number
Don't use your existing function - just call Math.random()
. If < 0.5 then -1, else 1:
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
I've always been a fan of
Math.round(Math.random()) * 2 - 1
as it just sort of makes sense.
Math.round(Math.random())
will give you 0 or 1Multiplying the result by 2 will give you 0 or 2
And then subtracting 1 gives you -1 or 1.
Intuitive!