Home > Web Front-end > JS Tutorial > Use js Math.random() function to generate random numbers between n and m_javascript skills

Use js Math.random() function to generate random numbers between n and m_javascript skills

WBOY
Release: 2016-05-16 16:34:29
Original
1609 people have browsed it

Summary:

This article explains how to use js to generate random numbers between n and m. The main purpose is to prepare for the later js generation of verification codes.

Math.random() function returns a pseudo-random number between 0 and 1, which may be 0 but is always less than 1, [0,1)

Generate n-m, integers including n but not m:

The first step is to calculate the value of m-n, assuming it is equal to w

The second step Math.random()*w

Step 3 Math.random()*w n

Step 4 parseInt(Math.random()*w n, 10)

Generate n-m, an integer that does not contain n but contains m: ​

The first step is to calculate the value of m-n, assuming it is equal to w

The second step Math.random()*w

Step 3 Math.random()*w n

Step 4 Math.floor(Math.random()*w n) 1

Generate n-m, an integer excluding n and m:

The first step is to calculate the value of m-n-2, assuming it is equal to w

The second step Math.random()*w

Step 3 Math.random()*w n 1

Step 4 Math.round(Math.random()*w n 1) or Math.ceil(Math.random()*w n 1)

Generate n-m, random numbers containing n and m:

The first step is to calculate the value of m-n, assuming it is equal to w

The second step Math.random()*w

Step 3 Math.random()*w n

Step 4 Math.round(Math.random()*w n) or Math.ceil(Math.random()*w n)

Example:

Generate a random integer between 800-1500, including 800 but not including 1500

Copy code The code is as follows:

1500-800 = 700
Math.random()*700
var num = Math.random()*700 800;
num = parseInt(num, 10);

It only takes four simple steps to complete.

Supplement:

Math.ceil() returns the smallest integer (rounding function) that is greater than or equal to the numeric parameter, and rounds the number up

Math.floor() returns the largest integer less than or equal to the numeric parameter, rounding the number down

Math.round() returns the number to the nearest integer, rounded

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template