Generate a negative random number using JavaScript

Maths

Ok, so you already know how to generate positive rondom numbers but let’s do it again:

To generate a random number varying from 0 to 9 we will use this code:

var randomN = Math.floor(Math.random()*10)

This expression on the right of the “=”

  1. produces a random number from 0 to 1 (excluding 1, say 0.917) with Math.random()
  2. multiplies it by 10 (9.71)
  3. removes decimals (9) with Math.floor

For negative values from -9 to 0 we will  simply subtract 9 from the previous result:

var negativeRandomN = Math.floor(Math.random()*10) - 9

Now what if you wanted a rondom integer from -10 to 20… ?
Yes you guessed it right! we will generate a random number from 0 to 30 then substact 10 from it

var randomN = Math.floor(Math.random()*31) - 10

So the rule is:
To generate a random integer from m to n, here is the code

var randomN = Math.floor(Math.random() * (n-m+1)) + m

Examples

# Random integer from 1 to 10
var randomN = Math.floor(Math.random() * 10) + 1

# Random integer from -100 to 100
var randomN = Math.floor(Math.random() * 201) -100

# Random integer from 0 to 255
var randomN = Math.floor(Math.random() * 256)

2 thoughts on “Generate a negative random number using JavaScript”

  1. Quick question: Can Math.floor() return a value that falls inside [0.99999999999999995, 0.99999999999999999]. Because if it can then the result for bounds [-100, 100] 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top