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:

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:

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

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

Examples

One comment on “Generate a negative random number using JavaScript

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">