Random number between two numbers javascript

How to generate random numbers between two numbers in JavaScript?

To generate a random number, we use the Math.random() function. This method returns a floating-point number in the range 0 (inclusive) to 1 (exclusive). To generate random numbers in different range, we should define the minimum and maximum limits of the range. Please follow the second syntax below for this.

To generate random integers, you can follow the third and fourth syntax discussed below.

As the Math.random() method gives us a random floating point number so to convert the result into an integer, we need to apply some basic math. Please follow the below syntaxes.

Syntax

Following is the syntax for generating a random number between two numbers −

  • Generate a random integer between two numbers min and max (both min and max are inclusive).
Math.floor(Math.random() * ((max-min)+1) + min);
  • Generate a random integer between two numbers min and max (the min is inclusive, and the max is exclusive).
Math.floor(Math.random() * (max-min) + min);

Here min and max are the start and end numbers between those we want to generate the random numbers.

Example 1

Generate a random number between 0 (inclusive) and 1 (exclusive).

In the example below, we generate a random number between 0 and 1. Here 0 in inclusive and 1 is exclusive.

html> body> h3>Genrate a random number between 0 (inclusinve) and 1 (exclusinve)/h3> p id="result">/p> script> var random = Math.random(); document.getElementById("result").innerHTML = random; /script> /body> /html>

Example 2

Generate many random numbers between 0 (inclusive) and 1 (exclusive).

In the example below, we generate 10 random numbers between 0 and 1. Here 0 is inclusive and 1 is exclusive.

html> body> h3>Genrate 10 random numbers between 0 (inclusinve) and 1 (exclusinve)/h3> p id="result">/p> script> for(var i =0; i 10; i++) var random = Math.random(); document.getElementById("result").innerHTML += random + "
"
; > /script> /body> /html>

Example 3

Generate a random number between two numbers.

In the example below, we generate a random number between 20 and 50.

html> body> h3>Genrate a random number between 20 and 50/h3> p id="result">/p> script> var min = 20; var max = 50 var random = Math.random() * (max - min) + min; document.getElementById("result").innerHTML += random ; /script> /body> /html>

Example 4

Generate many random numbers between two numbers.

In the example below, we generate 10 random numbers between 20 and 50.

html> body> h3>Genrate 10 random number between 20 and 50/h3> p id="result">/p> script> var min = 20; var max = 50; for(var i =0; i 10; i++) var random = Math.random() * (max - min) + min; document.getElementById("result").innerHTML += random + "
"
; > /script> /body> /html>

Notice that up to now; the generated random numbers are floating point numbers. Now let’s see how to generate random integers.

Example 5

Generate a random integer between two numbers.

In the below example, we generate a random integer between 10 and 100.

html> body> h3>Genrate a random integer between10 and 100/h3> p id="result">/p> script> function randomInt(min, max) min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; > document.getElementById("result").innerHTML = randomInt(10,100); /script> /body> /html>

Example 6

In the below example, we take the two numbers from the user. We generate a random number between these two numbers.

html> body> h3>Generate Random Number Using JavaScript/h3> div style="display: inline-block;">Random Number Between input type="text" class="start"> and input type="text" class="end">/div> br />br /> input type="button" value="Get Number" onclick="getRandomNumber();"> p class="number">/p> script> function getRandom(start,end) return Math.floor(Math.random()*(end-start+1))+start; > function getRandomNumber() var start = document.getElementsByClassName('start')[0].value; var end = document.getElementsByClassName('end')[0].value; document.getElementsByClassName('number')[0].innerHTML = 'The Random Number is : '+getRandom(parseInt(start),parseInt(end))+''; > /script> /body> /html>

Example 7

Generate many random integers between two numbers.

In the below example, we generate 10 random integers between 10 and 100.

html> body> h3>Generate 10 random integers between 10 and 100/h3> p id="result">/p> script> function randomInt(min, max) min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; > for (var i = 0; i 10; i++) document.getElementById("result").innerHTML += randomInt(10, 100) + "
"
; > /script> /body> /html>

In this tutorial, we discussed ways to generate random numbers between two numbers. We saw how to generate a single as well as many random numbers between two numbers. We generated random numbers as floating-point and integers.

Источник

Math.random()

The Math.random() static method returns a floating-point, pseudo-random number that’s greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

Note: Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

Try it

Syntax

Return value

A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

Examples

Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random() itself) aren’t exact. If extremely large bounds are chosen (2 53 or higher), it’s possible in extremely rare cases to reach the usually-excluded upper bound.

Getting a random number between 0 (inclusive) and 1 (exclusive)

function getRandom()  return Math.random(); > 

Getting a random number between two values

This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min , and is less than (and not equal) max .

function getRandomArbitrary(min, max)  return Math.random() * (max - min) + min; > 

Getting a random integer between two values

This example returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn’t an integer), and is less than (but not equal to) max .

function getRandomInt(min, max)  min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive > 

Note: It might be tempting to use Math.round() to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs.

Getting a random integer between two values, inclusive

While the getRandomInt() function above is inclusive at the minimum, it’s exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The getRandomIntInclusive() function below accomplishes that.

function getRandomIntInclusive(min, max)  min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1) + min); // The maximum is inclusive and the minimum is inclusive > 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Mar 28, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

How TO — Random Number Between Two Numbers

Learn how to get a random number between two numbers in JavaScript.

Random Numbers

This JavaScript function always returns a random number between a minimum (included) and maximum number (excluded):

Example

This JavaScript function always returns a random number between min and max (both included):

Example

Read more about Random Numbers in our JavaScript Random Tutorial.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Generate a Random Number Between Two Numbers in JavaScript

Generate a Random Number Between Two Numbers in JavaScript

  1. Generate a Random Number Between 1 and User-Defined Value in JavaScript
  2. Generate a Random Number Between Two Numbers in JavaScript

This tutorial will learn how to generate a random number between two numbers in JavaScript. We will use the method Math.random() that generates a random floating number between 0.0 and 0.999 .

Generate a Random Number Between 1 and User-Defined Value in JavaScript

We can generate a random number in JavaScript using a random number generator — Math.random() , by multiplying the generated float number with the maximum number we want to generate. Math.random()* max generates a random number between 0 and max .

function generateRandom(max)  return Math.random() * max; >  console.log("1st try: "+generateRandom(5)); console.log("2nd try: "+generateRandom(5)); console.log("3rd try: "+generateRandom(5)); console.log("4th try: "+generateRandom(5)); 
1st try: 3.3202340813091347 2nd try: 1.9796467067025836 3rd try: 3.297605748406279 4th try: 1.1006700756032417 

If we want to get only the result in integer format, we can use Math.floor() , this method returns the largest integer less than or equal to the input number.

console.log(Math.floor(1.02)); console.log(Math.floor(1.5)); console.log(Math.floor(1.9)); console.log(Math.floor(1)); 

By using the Math.floor() method we can get our randomly generated integers,

function generateRandomInt(max)  return Math.floor(Math.random() * max); >  console.log("1st Integer try: "+generateRandomInt(9)); console.log("2nd Integer try: "+generateRandomInt(9)); console.log("3rd Integer try: "+generateRandomInt(9)); console.log("4th Integer try: "+generateRandomInt(9)); 
1st Integer try: 8 2nd Integer try: 5 3rd Integer try: 7 4th Integer try: 0 

Generate a Random Number Between Two Numbers in JavaScript

If we also want to have a user-defined minimum value, we need to change the equation of Math.random() * max to Math.random() * (max-min)) +min . Using this equation the returned value is a random number between min and max .

function generateRandomInt(min,max)  return Math.floor((Math.random() * (max-min)) +min); >  console.log("1st min and max try: "+generateRandomInt(2,9)); console.log("2nd min and max try: "+generateRandomInt(2,9)); console.log("3rd min and max try: "+generateRandomInt(2,9)); console.log("4th min and max try: "+generateRandomInt(2,9)); 
1st min and max try: 6 2nd min and max try: 2 3rd min and max try: 8 4th min and max try: 3 

In case we are interested in having the max value to be included in our random generator scope, we need to change the equation to (Math.random() * (max+1 — min)) +min . Adding 1 to max-min will include the max in range and Math.floor() will always guarantee that this value is not more than the max .

function generateRandomInt(min,max)  return Math.floor((Math.random() * (max+1 -min)) +min); >  console.log("1st min and max included try: "+generateRandomInt(2,9)); console.log("2nd min and max included try: "+generateRandomInt(2,9)); console.log("3rd min and max included try: "+generateRandomInt(2,9)); console.log("4th min and max included try: "+generateRandomInt(2,9)); 
1st min and max included try: 3 2nd min and max included try: 7 3rd min and max included try: 9 4th min and max included try: 6 

Related Article — JavaScript Number

Источник

Читайте также:  Serial com port python
Оцените статью